是全局常数不能在while循环中使用?



全局常量不能在while循环中使用吗?

EASY_ATTEMP = 10 
HARD_ATTEMP = 5 
random_number = random.randint(1, 100)
difficulty = "easy"
if difficulty == "easy":
attemp = EASY_ATTEMP
already_finished = False
while not already_finished:
print(f"You have {attemp} attempts reamaining to guess the number")  #<--here
guess = int(input("Make a guess: "))

显示如下错误:

Traceback (most recent call last):
File "main.py", line 21, in <module>
print(f"You have {attemp} attempts reamaining to guess the number")
NameError: name 'attemp' is not defined

怎么回事?

我复制了代码并尝试运行它,但没有错误。我不知道问题是什么,但我建议让你的代码更整洁。"

attemp = 5
random_number = random.randint(1, 100)
difficulty = input('Do you want easy difficulty? Y or N?')
if difficulty in  "Yy":
attemp = 10
while attemp > 0:
print(f"You have {attemp} attempts reamaining to guess the number")  #<--here
guess = int(input("Make a guess: "))
if guess == random_number:
break
attemp -= 1

"

例如,在while循环中,您可以使用try变量创建一个布尔值,并在每次迭代中减少1。变量' try '将始终评估为一个容易的难度,因为变量难度总是引用'easy' str。我不确定你想要代码如何运行,但在上面的代码中我设置了它,以便用户可以决定。

最新更新