2016-10-03 43 views
1

我想从键盘读取一个数字并验证它我如何通过Python中的函数传输变量

这是我所拥有但它不起作用。

没有错误,但它不记得数我介绍

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) 
+1

''''''''''''''''''''''''''''''''''''''read'你似乎已经知道如何使用'return',为什么不在'read()'中使用它呢? –

+0

从'read'返回数字并将'a'重新赋值给返回的值 –

回答

0

看来好像你不返回read()函数的结果。

你读功能的最后一行应该是“返回”

然后当你调用read函数,你会说:“一个=阅读()”

1

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) 
+1

写'while'行不是IsInteger(a)'的更好方法'。通常,最好避免显式测试“True”或“False”。请参阅[PEP-0008编程建议](https://www.python.org/dev/peps/pep-0008/#programming-recommendations),“不要使用==比较布尔值为True或False”。另外,在'try'模块中,你不需要做这个赋值,'int(b)'本身可以正常工作。 OTOH,我想这可能会让一些读者感到困惑。 :) –

+0

@ PM2Ring好点。我已经编辑了'while IsInteger(a)'解决方案。 –

1

我认为这是你正在努力实现的。

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()内。

但我会强烈推荐 u到使用return,并重新分配“A”的值,如下面的人说。

+1

尽管这会起作用,但使用全局变量在Python中通常被认为是一个糟糕的解决方案。 –

+0

我知道。这就是为什么我只是添加我的意见,他应该使用'return'重新分配的方式。 – Nf4r