简体   繁体   中英

Python: Can nested function change global variables?

# Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. (Hint: remember to use the user input lessons from the very first exercise)

# Extras:

# Keep the game going until the user types “exit”
# Keep track of how many guesses the user has taken, and when the game ends, print this out.
import random
counter = True

tooHigh = "You've guess too high"
justRight = "You've guessed correctly!"
tooLow = "You've guessed too low"

def generatedNumber():
    genValue = random.randint(1,9)
    return genValue
def guessTheNumber():
    guessedNumber = input("Guess a number between 1 and 9: ")
    if guessedNumber in "0123456789":
        guessedNumber = int(guessedNumber)
        print(type(guessedNumber))
    else:
        guessedNumber = 0
    return guessedNumber

def makeFalse():
    counter = False

def guessesComparer(computerNumber, userNumber):
    if userNumber == 0:
        makeFalse()
    elif computerNumber == userNumber:
        print(justRight)
    elif computerNumber > userNumber:
        print(tooLow)
    elif computerNumber < userNumber:
        print(tooHigh)

def mainAction():
    computerNumber = generatedNumber()
    userNumber = guessTheNumber()
    guessesComparer(computerNumber, userNumber)

while (counter == True):
    mainAction()

I'm simply wondering how I would get a nested function to change a global variable or if it's possible? I wanted to end the while loop at the end when the user types "exit", but I don't know how to switch the "counter" variable to false. I know there's a much simpler way to do this if I start the code over and do it in a different way, but I'm just trying to become good enough to do it multiple ways.

Yes, you can assign values to globals in any function if you declare global X before any assignment to that name then any assignment X = Y rather than binding a function local assigns a value to the global.

But it would be better to make an object out of those functions and store the state as instance variables rather than global variables.

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