Jacob England Jacob England -4 years ago 154
Python Question

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

Answer Source

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   
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download