[英]Python - Trying to use the value of a name from one module in a different module
I'm a newbie at programming. 我是编程的新手。 Going to fire that one straight out there.
要直接开除那人。 Now I'm going to list three modules of code:
现在,我将列出三个代码模块:
def GCD(x,y):
#gives the Greatest Common Divisor of two values.
while y != 0:
r = x
while r >= y: #these two lines are used to
r -= y #calculate remainder of x/y
x = y
y = r
print x
This is the original program I wrote, based on Euclidean Algorithm for GCD. 这是我基于GCD的欧几里得算法编写的原始程序。 It functions correctly.
它正常运行。 I now want to remove the two commented lines above and replace it with a call to a further module I made, which calculates the remainder:
现在,我想删除上面的两条注释行,并用对我制作的另一个模块的调用来替换它,该模块将计算余数:
Remainder Calculator 余数计算器
def xy(x, y):
#Gives the remainder of the division of x by y. Outputs as r.
while x >= y:
x -= y
r = x
This program also functions correctly. 该程序也可以正常运行。 I want to use the value of the name 'r' in my edited program.
我想在编辑后的程序中使用名称“ r”的值。 I have attempted to do this below, but it causes problems:
我试图在下面执行此操作,但是会导致问题:
def GCD(x,y):
import remainder
#gives the Greatest Common Divisor of two values.
while y != 0:
remainder.xy(x,y)
from remainder import r #here is the problem. This line is my attempt at
#importing the value of r from the remainder calculating
#module into this module. This line is incorrect.
x = y
y = r #Python cannot find 'r'. I want to use the value for 'r' from the execution
#of the remainder calculating module. Attempts to find how have been
#unsuccessful.
print x
I need to find out how to use the calculated value of 'r' from my xy module in my second GCD module. 我需要找出如何在第二个GCD模块中的xy模块中使用“ r”的计算值。 I have tried using
我尝试使用
global r
in my module though I have had no success. 在我的模块中,虽然我没有成功。 I'm not sure if I am interpreting the function of 'global' correctly.
我不确定我是否正确解释了'global'的功能。
I would appreciate your help. 多谢您的协助。
Jet Holt 杰特·霍尔特
If I understand you correctly: 如果我正确理解您的意见:
from remainder import xy
def GCD(x,y):
#gives the Greatest Common Divisor of two values.
while y != 0:
r = xy(x,y)
x = y
y = r
print x
and 和
def xy(x, y):
#Gives the remainder of the division of x by y. Outputs as r.
while x >= y:
x -= y
return x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.