首页 > 解决方案 > 函数外的布尔值不会改变

问题描述

我正在学习 Python,无法在我的函数bool中将“True”更改为“False” 。replay我搜索了 StackOverflow,但找不到答案。

我试过canPlay = FalsecanPlay = 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()

标签: pythonpython-3.xscope

解决方案


使用函数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函数外的其他语句访问。


推荐阅读