函数外的布尔值不会改变
Boolean value outside the function doesn't get changed
我正在学习 Python,但无法让我的 bool
在我的 replay
函数中从“True”变为“False”。我搜索了 Whosebug,但找不到答案。
我试过 canPlay = False
和 canPlay = not canPlay
。但那是行不通的。
有什么建议吗?
import random
from random import randint
# welcome message
print("Welcome to the number guessing game!")
# get the random seed
seedValue = input("Enter random seed: ")
random.seed(seedValue)
canPlay = True
def play():
randomNumber = randint(1, 100)
numberOfGuesses = 1
guessValue = ""
while guessValue != randomNumber:
# prompt the user for a guess
guessValue = int(input("\nPlease enter a guess: "))
# provide higher/lower hint
if guessValue == randomNumber:
print(f"Congratulations. You guessed it!\nIt took you {numberOfGuesses} guesses.")
elif guessValue > randomNumber:
print("Lower")
else:
print("Higher")
# increment the count
numberOfGuesses += 1
def replay():
playAgain = input("\nWould you like to play again (yes/no)? ")
if playAgain == "no":
canPlay = False # not changing values
canPlay = not canPlay # this doesn't work either
print("Thank you. Goodbye.")
while canPlay == True:
play()
replay()
在 reply()
函数中使用 global
关键字,您可以更改全局命名空间中 canPlay
变量的值,然后在 while 语句 while canPlay == True:
:
def replay():
global canPlay # <------------------ Here
playAgain = input("\nWould you like to play again (yes/no)? ")
if playAgain == "no":
canPlay = False # not changing values
canPlay = not canPlay # this doesn't work either
print("Thank you. Goodbye.")
如果不插入该行,canPlay
将是 reply()
函数的局部变量,因此它不能更改全局变量或被 [=17 之外的其他语句访问=]函数。
我正在学习 Python,但无法让我的 bool
在我的 replay
函数中从“True”变为“False”。我搜索了 Whosebug,但找不到答案。
我试过 canPlay = False
和 canPlay = not canPlay
。但那是行不通的。
有什么建议吗?
import random
from random import randint
# welcome message
print("Welcome to the number guessing game!")
# get the random seed
seedValue = input("Enter random seed: ")
random.seed(seedValue)
canPlay = True
def play():
randomNumber = randint(1, 100)
numberOfGuesses = 1
guessValue = ""
while guessValue != randomNumber:
# prompt the user for a guess
guessValue = int(input("\nPlease enter a guess: "))
# provide higher/lower hint
if guessValue == randomNumber:
print(f"Congratulations. You guessed it!\nIt took you {numberOfGuesses} guesses.")
elif guessValue > randomNumber:
print("Lower")
else:
print("Higher")
# increment the count
numberOfGuesses += 1
def replay():
playAgain = input("\nWould you like to play again (yes/no)? ")
if playAgain == "no":
canPlay = False # not changing values
canPlay = not canPlay # this doesn't work either
print("Thank you. Goodbye.")
while canPlay == True:
play()
replay()
在 reply()
函数中使用 global
关键字,您可以更改全局命名空间中 canPlay
变量的值,然后在 while 语句 while canPlay == True:
:
def replay():
global canPlay # <------------------ Here
playAgain = input("\nWould you like to play again (yes/no)? ")
if playAgain == "no":
canPlay = False # not changing values
canPlay = not canPlay # this doesn't work either
print("Thank you. Goodbye.")
如果不插入该行,canPlay
将是 reply()
函数的局部变量,因此它不能更改全局变量或被 [=17 之外的其他语句访问=]函数。