Python—尝试在不同的模块中使用来自一个模块的名称值

Python—尝试在不同的模块中使用来自一个模块的名称值,python,Python,我是个编程新手。我要直接把那一枪开出去。现在我将列出三个代码模块: 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 这是

我是个编程新手。我要直接把那一枪开出去。现在我将列出三个代码模块:

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
这是我写的原始程序,基于GCD的欧几里德算法。它工作正常。现在,我想删除上面的两行注释,并将其替换为对我所做的另一个模块的调用,该模块将计算剩余部分:

余数计算器

def xy(x, y):
#Gives the remainder of the division of x by y. Outputs as r.
   while x >= y:
       x -= y
   r = x
该程序也能正常运行。 我想在编辑的程序中使用名称“r”的值。我已尝试在下面执行此操作,但它会导致问题:

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
我需要了解如何在第二个GCD模块中使用xy模块中计算出的“r”值。我试过使用

global r
在我的模块中,虽然我没有成功。我不确定我是否正确解释了“全局”的功能

谢谢你的帮助


杰特霍尔特

如果我理解正确:

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


为什么不让余数函数返回
r
而不是尝试设置它?
global
为名称提供了模块级范围,而不是绝对全局范围。是的,你误解了它的功能。返回
r
,而不是设置它。如果可以的话,你不应该使用
global
。谢谢,Return做了我想做的。正如我提到的,我是一个完全的新手,不知道返回的目的是“发送数据”。杰特·霍尔特。@JetHolt不用担心。现在您知道了——从现在开始,尝试将这种心态应用到Python代码中。一个有用的提示:函数中参数的名称不必与传入的变量的名称相同,事实上,它们之间没有任何关系。此外,当您将一个变量作为参数传入时,您会复制它的
id
,因此它实际上不是通过引用调用的,并且内部版本具有函数作用域的本地版本。为什么在其中有
from rements import r
?什么是
r
?如果它真的在那里,它将隐藏以前的
r
值,如果它不在那里,你将得到一个
ImportError
+1^我做了一个快速复制和粘贴工作,但在浏览代码时错过了它。我把它拿出来,谢谢你的接球
def xy(x, y):
#Gives the remainder of the division of x by y. Outputs as r.
   while x >= y:
       x -= y
   return x