stackoverflow新手,python(python-3)新手。目前正在edx.org上学习并遇到以下错误。
我创建了一个功能,根据 str 检查用户输入 str 并返回 True 或 False
测试该功能时,我创建了一个 while 循环,以便在第3次尝试失败时停止。但是,每当尝试失败时,该函数只打印错误消息两次,只打印一次。
我通过将函数的返回 Bool 值存储到变量中而不是直接在中的 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 : ")
答案 0 :(得分:1)
您想在input()
循环中调用while
:
# ...
answer2 = "m"
i = 0
while i < 3:
guess2 = input("Please enter a single alphabet : ")
# ...
否则,用户无法更改答案,guess2
永远不会更改,并且会多次收到相同的错误消息。
答案 1 :(得分:0)
你调用该函数两次,首先在if和in elif中,使用相同的错误猜测。你修正了它只调用一次并存储返回值。
我试着更好地解释它:该函数总是被第一个调用if来评估它的条件;如果返回值为false,则再次调用以评估elif条件,使用与之前相同的参数。