如何在函数中请求用户输入并将其返回到def main():?

时间:2017-03-23 02:16:36

标签: python input

我需要在以下函数中询问用户输入并将n返回到main。变量n将在main / other函数中使用。然而,每当我这样做时,我收到一条错误消息,指出n未定义。为什么以下功能不能正常工作?

def main():    
    intro()  
    setInput()  
    print "\nThe prime numbers in range [2,%d] are: "%(n)  
    for i in range(n):  
    if testPrime(i):  
    print i,",",     
def setInput():      
    n = input("Enter the value for what range to find prime numbers: ")     
    return n  

2 个答案:

答案 0 :(得分:1)

main()来电中,您需要将setInput()的结果存储为n,如下所示:

def setInput():      
    n = input("Enter the value for what range to find prime numbers: ")     
    return n  

def main():    
    intro()  
    n = setInput()  
    print "\nThe prime numbers in range [2,%d] are: "%(n)  
    for i in range(n):  
        if testPrime(i):  
            print i,",",     

注意for循环后的缩进。我认为这就是你的意图。

此外,由于您使用的是Python 2.x,因此使用raw_input()然后将字符串转换为正确的类型会更安全。例如,你可以这样做:

s = raw_input("Enter the value for what range to find prime numbers: ") 
n = int(s)    # or fancier processing if you want to allow a wider range of inputs   

答案 1 :(得分:0)

您可以使用global关键字...

def setInput():
    global n
    n = input("Enter the value for what range to find prime numbers: ")
    return n

即使在函数之外也可以访问该变量(在每个函数之外执行n = "something"具有相同的效果。

n = 42

def foo():
    print(n)    # getting the value on n is easy
    return n+1  # same here

def bar():
    global n
    n += 10     # setting a value to n need the use of the keyword (one time per function)

if __name__ == "__main__":
    print(n)  # 42

    a = foo() # 42
    print(a)  # 43

    print(n)  # 42
    bar()
    print(n)  # 52

直接从main调用此函数,并在参数中传递n(更冗余,但更安全......这取决于变量的作用:使用类似n的名称,使用全局变量似乎不是一个好选择,但选择取决于你)

def main():
    ...
    n = setInput()
    foo(n)
    ...