繁体   English   中英

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

[英]How to ask for user input within a function and return it to def main():?

我需要在以下函数中要求用户输入并将n返回给main。 变量n将在主要/其他功能中使用。 但是,无论何时执行此操作,我都会收到一条错误消息,指出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  

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   

您可以使用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的名称,使用a似乎不是一个好选择全局变量,但选择取决于您)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM