python - 为什么当我将状态设置为 false 时程序没有跳出 while 循环?
问题描述
我是 python 新手,我只是在创建一个简单的随机数猜谜游戏。
简单地说,要跳出 while 循环,用户必须猜测正确的数字或达到最大尝试次数,即 3
但是,当我调用该函数来检查尝试的次数时,代码似乎并没有打破循环。有没有办法摆脱调用函数的while循环?
...
import random
print("*** RANDOM NUMBER GUESSING ***\n")
print("1. Guess the number between x and y.")
print("2. You have 3 attempts to guess the random number.\n")
x = input("The random number is generated between x: ")
x = int(x)
y = input ("and y: ")
y = int(y)
#Random number generated
randNum = random.randint(x,y)
userAttempts = 0
gameState = True
#Function checking the attempts made
#If max attempts reached then gameState = False to break out of the while loop
def maxAttempts(attempts, state):
if attempts == 3:
print("Max attempts reached!")
state = False
return state
while gameState:
userNum = input("Guess the random: ")
userNum = int(userNum)
if userNum == randNum:
print("Well done you guessed the correct number !!")
gameState = False;
elif userNum > randNum:
print("Number is too high")
userAttempts += 1
maxAttempts(userAttempts, gameState)
#debugging
print("Attempts: ", userAttempts)
print("Game state: ", gameState)
else:
print("Number is too low")
userAttempts += 1
maxAttempts(userAttempts, gameState)
#debugging
print("Attempts: ", userAttempts)
print("Game state: ", gameState)
print("\nGame finished.\n")
解决方案
当您更新state
时maxAttempts
,您只是更改了局部变量的值state
。
def flip(state):
state = False if state else True
state = True
flip(state)
print(state) # => True
您想要返回更新的值并重新分配它,遵循更实用的纯函数方法:
def flip(state):
return False if state else True
state = True
state = flip(state)
print(state) # => False
推荐阅读
- c - (C) 获取安全的 int 输入
- angular - 仅在 if 语句中无法使用 MQTT 读取 Ionic 中未定义的属性“推送”
- swift - Xcode10 - dyld:没有为框架中安装的 pod 加载库
- c++ - 使用模板特化拆分可变参数包
- javascript - 按钮单击不会更新我的 React 应用程序中的状态
- azure - Azure DevOps 发布部署失败磁盘空间错误
- openrefine - 如何匹配数据集之间的条目?
- javascript - jQuery Ajax 请求内容的下载为空
- r - Tidy Eval,使用 enquo 和 infer 包
- swift - 如何使用从 Core Data 创建的 NSSet