如何在Python中通过函数传递变量

如何在Python中通过函数传递变量,python,variables,Python,Variables,我正在尝试从键盘读取一个数字并验证它 这是我有的,但不起作用 没有错误,但它不记得我介绍的号码 def IsInteger(a): try: a=int(a) return True except ValueError: return False def read(): a=input("Nr: ") while (IsInteger(a)!=True): a=input("Give a numb

我正在尝试从键盘读取一个数字并验证它

这是我有的,但不起作用

没有错误,但它不记得我介绍的号码

def IsInteger(a):
    try:
        a=int(a)
        return True
    except ValueError:
        return False 

def read():
    a=input("Nr: ")
    while (IsInteger(a)!=True):
        a=input("Give a number: ")

a=0
read()
print(a)

看起来好像您没有返回read()函数的结果

def IsInteger(b):
    try:
        b=int(b)
        return True
    except ValueError:
        return False 

def read():
    a=input("Nr: ")
    while not IsInteger(a):
        a=input("Give a number: ")
    return a

c = read()
print(c)
read函数的最后一行应该是“returna”


然后,当调用read函数时,您会说“a=read()”

a
是这两个函数的局部变量,其他代码无法看到它。修复代码的最佳方法是从
read()
函数返回
a
。此外,在
IsInteger()
函数中,间距是关闭的

def IsInteger(b):
    try:
        b=int(b)
        return True
    except ValueError:
        return False 

def read():
    a=input("Nr: ")
    while not IsInteger(a):
        a=input("Give a number: ")
    return a

c = read()
print(c)

我想这就是你想要达到的目标

def IsInteger(a):
    try:
        a=int(a)
        return True
    except ValueError:
        return False 

def read():
    global a
    a=input("Nr: ")
    while (IsInteger(a)!=True):
        a=input("Give a number: ")

a=0
read()
print(a)
您需要使用
global
表达式来覆盖全局变量,而无需在函数内创建
return
并键入
a=read()


但是我强烈建议你使用
返回
并重新分配“a”的值,正如下面有人所说。

a
读取()中的全局名称和
a
本地名称是独立的变量。您似乎已经知道如何使用
return
,为什么不在
read()
中使用它呢?
返回
read
中的数字,并将
a
重新分配给返回的值。虽然这会起作用,但在Python中使用全局变量通常被认为是一个糟糕的解决方案。我知道。这就是为什么我刚才添加了我的观点,他应该使用带有
return
的重新分配方式。编写
while
行的更好方法是
而不是IsInteger(A)
。通常,最好避免针对
True
False
进行显式测试。请参阅“不要使用==”将布尔值与True或False进行比较”。另外,在
try
块中,您不需要执行该赋值,
int(b)
本身就可以正常工作;奥托,我想这对一些读者来说可能有点困惑@PM2Ring有很多优点。我在
中进行了编辑,而不是在IsInteger(a)
解决方案中进行编辑。