首页 > 解决方案 > 为什么当我将状态设置为 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")

标签: pythonrandom

解决方案


当您更新statemaxAttempts,您只是更改了局部变量的值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

推荐阅读