简体   繁体   中英

Variable value contained within function in Python

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?

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.

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()

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()

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