简体   繁体   中英

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

I need to ask the user for input within the following function and return n to main. The variable n will be used within main/other functions. Whenever I do this however, I get an error message saying that n is undefined. Why doesn't the following function work as I need it to?

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  

In the main() call, you need to store the result of setInput() as n like this:

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,",",     

Note the indentation after the for loop. I think this is what you intended.

Also, since you are using Python 2.x, it would be safer to use raw_input() and then convert the string to the correct type. For example, you could do:

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   

You could use the global keyword...

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

The variable will be accessible even outside the functions (doing a n = "something" outside of every function has the same effect.

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

Or call this function from the main directly, and pass n in the arguments (more redundant, but safer... it depends on the role of the variable : with a name like n , it seems not to be a good choice to use a global variable, but the choice is up to you)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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