1

I am writing a program in which I have the function guessgetter defined like this:

def guessgetter():
    print("What number do you choose?")
    num = int(input())
    if num > 100 or num < 1:
        print("Please choose a number between 1 and 100")
        guessgetter()

I know that this syntax is valid. However, when I refer later on in the code (yes, after running the function I created) to num, it says that I have not defined a value for it. How can I fix this?

3 Answers 3

3

The issue is that while num is defined in the scope of the function guessgetter, it isn't defined elsewhere in your code. If you want to use the value of num generated by the function, try adding as the last line of your function

return num

and then calling the function as follows:

x = guessgetter()

to store the value that you get into a variable x that can be used outside of the function.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to return the value from the function, and capture the returned value when you call the function. You also need to deal with the tail recursion. This leads to:

def guessgetter():
    print("What number do you choose?")
    num = int(input())
    if num > 100 or num < 1:
        print("Please choose a number between 1 and 100")
        num = guessgetter()
    return num

You can use it as:

guess = guessgetter()

2 Comments

Recursion in a case like this isn't really Pythonic (Python doesn't do tail call elimination, even when it would be possible). Use a while loop instead: while num > 100 or num < 1: num = int(input("Please choose a number between 1 and 100"))
I agree that the recursion should be replaced by a while loop; I left it more or less as it was just to illustrate that the return value from the recursive call has to be captured too — if you keep the recursive call.
0

Outside of the scope of the function guessgetter, the variable num does not exist. If you would later like to know what the value of num is, you would have to make the variable num global (that is, accessible everywhere). The easiest way to do this is to add the line

global num

to your function before num is assigned:

def guessgetter():
    print "What number do you choose?"
    global num
    num = int(input())
    if num > 100 or num < 1:
        print("Please choose a number between 1 and 100")
        guessgetter()

2 Comments

Are you sure global variables of any sort are Pythonic?
Yeah, probably not. This does, however, solve the problem without altering any other lines of code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.