因此下面的代码提供了一个输入,根据过去的猜测,检查输入是否为一个字符长,并查看它是否为字母。否则,它应该返回该消息以重试。但是,在尝试代码时,我仅获得else条件,而无法获得if条件(应返回结果)。有谁知道为什么以及如何解决这个问题?
def get_guess(past_guesses):
"""
Checks if past_guesses is 1 letter, a letter or has been used before, and
prompts user to try again
Example:
>>> get_guess(['A', 'a', 'c', 'd'])
'You need to enter one alphabetic character which you haven't\
already guessed. Try again'
>>> get_guess(['a', 'b', 'c', 'd'])
'a'
"""
answer = "'You need to enter one alphabetic character which you haven't\
already guessed. Try again'"
while True:
guess = input("Guess a letter: ")
if guess.isalpha() and len(guess) == 1 and guess not in past_guesses:
past_guesses.append(guess)
return guess
else:
print (answer)
答案 0 :(得分:0)
Return不打印pass_guesses
,它从函数中返回值,如果要使用它,则需要将其分配给变量。
a = get_guess(['A', 'a', 'c', 'd'])
print(a)
答案 1 :(得分:0)
也许这就是您要寻找的。您的代码运行正常。您必须打印返回的结果。
print get_guess(['A', 'a', 'c', 'd'])
答案 2 :(得分:0)
您如何打get_guess()
?当您收到提示Guess a letter:
时,如果您输入的字符不是一个字符,则您的代码将在else
子句之后运行。
例如,如果在收到提示后键入abc
,则abc
不是一个字符,因此您将转到else子句并打印answer