# 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()
我只是想知道如何获得嵌套函数来更改全局变量或者它是否可能?我想在用户输入&#34;退出&#34;时结束while循环,但我不知道如何切换&#34;计数器&#34;变量为false。我知道,如果我开始使用代码并以不同的方式执行此操作,则可以采用更简单的方法,但我只是想要变得足够好以多种方式执行此操作。
答案 0 :(得分:0)
是的,如果在对该名称进行任何赋值之前声明global X
,则可以为任何函数中的全局变量分配值,然后任何赋值X = Y
而不是绑定函数local为全局赋值。
但最好从这些函数中创建一个对象,并将状态存储为实例变量而不是全局变量。