从列表中选出一个选项
问题描述:
我无法返回列表选项。从列表中选出一个选项
例如:
Fruits = {
'Apple': Apple, 'Banana': Banana, 'Orange': Orange}
def Choose_Fruit():
Choice = input('Choose a fruit: ')
if Choice not in Fruits:
Choose_Fruit()
return Choice
如果我输入 'Appppple',这将迫使我重新选择。如果我然后键入'Apple',它会成功返回Choice,但是如果我打印它,则会返回'Appppple'而不是'Apple'。它打印第一个输入,而不是满足if语句的输入。
答
非常简单的解决办法是从你的递归调用返回Choose_Fruit
。
# there isnt much point this being a dict.
Fruits = {'Apple': 'Apple', 'Banana': 'Banana', 'Orange': 'Orange'}
def Choose_Fruit():
Choice = input('Choose a fruit: ')
if Choice not in Fruits:
return Choose_Fruit()
return Choice
print(Choose_Fruit())
从任何递归调用当前的返回值被丢弃,并在第一次迭代的输入值存储在所有情况下返回。
它将始终返回第一次尝试的值,但不捕获递归调用的返回值。为了解决这个问题,从递归调用返回到'Choose_Fruit',例如'返回Choose_Fruit()'。除此之外,有更好的方法来实现你想要看到[这里](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) 。 –
你正在抛弃'Choose_Fruit()'的结果 –