当我将状态设置为false时,为什么程序没有跳出while循环?

2024-09-18 18:44:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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")

Tags: thefalsenumberinputisrandomintstate
3条回答

maxAttempts中更新state时,只需更改局部变量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

您正在maxAttempts函数中设置state = False。 我想你是在假设这会自动生成gameState = False。 这是不正确的。 您必须将函数调用为:

gameState = maxAttempts(userAttempts, gameState)

因为方法返回state的值,所以需要将这个新值赋给变量。将两个相关行更改为:

gameState = maxAttempts(userAttempts, gameState)

编辑: 在检查其他答案后,我意识到您的函数定义缺少以下内容:

else:
    return True

相关问题 更多 >