python - 函数外的布尔值不会改变
问题描述
我正在学习 Python,无法在我的函数bool
中将“True”更改为“False” 。replay
我搜索了 StackOverflow,但找不到答案。
我试过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()
解决方案
使用函数global
内的关键字reply()
,您可以更改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()
函数的局部变量,因此它不能更改全局变量或被reply
函数外的其他语句访问。
推荐阅读
- javascript - 在 React 中循环遍历二维数组
- oracle - Oracle Forms 12c - BI Publisher 集成错误
- android - 当我迁移到 androidx 时无法访问类 android.support.v4.app.FragmentActivity
- sql-server - 如果所有值都是大写,是否需要大写索引?
- excel - 将短日期转换为长日期
- perl - 如何确定用户在 perl 脚本中是否有 ssh 密钥
- solr - Nutch regex-urlfilter 不起作用
- clojure - 用宏解析中缀字符串
- mysql - 将文本时间戳转换为 MySQL 中所有行的日期时间
- html - flexbox 全宽表格