gpt4 book ai didi

python - 为什么这会打印两次错误消息?

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:55 28 4
gpt4 key购买 nike

stackoverflow 新手,以及 python (python-3) 新手。目前在 edx.org 上学习并遇到以下错误。

我创建了一个函数,用于根据答案 str 检查用户输入的 str 并返回 TrueFalse>.

在测试该函数时,我创建了一个 while 循环以在第三次不成功的尝试时停止。但是,每当尝试不成功时,该函数就会将错误消息打印两次,而实际上它应该只打印一次。

我通过将函数返回的 Bool 值存储到变量中来修复错误,而不是直接在 while< 内的 if 条件中调用该函数/strong> 循环。但是,我想了解错误消息打印两次背后的逻辑。这是打印错误消息两次的原始代码:

def letter_guess(letter, guess):

if len(guess) == 1 and guess.isalpha() and guess < letter:
print(guess,"is lower than the answer. Try again.\n")
return False

elif len(guess) == 1 and guess.isalpha() and guess > letter:
print(guess,"is higher than the answer. Try again.\n")
return False

elif len(guess) == 1 and guess.isalpha() and guess == letter:
print("Correct answer!")
return True

else:
print("Please only enter one alphabet for the letter. Try again.\n")
return False

answer2 = "m"
guess2 = input("Please enter a single alphabet : ")

i = 0

while i < 3:


if letter_guess(answer2, guess2):
break

elif letter_guess(answer2, guess2) == False and i == 2:
print("You have reached 3 guesses. Game over.")
break

else:
i += 1
guess2 = input("Please guess again : ")

最佳答案

您想在 while 循环内调用 input():

# ...
answer2 = "m"
i = 0
while i < 3:
guess2 = input("Please enter a single alphabet : ")
# ...

否则用户没有机会更改他们的答案,guess2 永远不会更改,并且他们会多次收到相同的错误消息。

关于python - 为什么这会打印两次错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47563637/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com