我无法返回列表选项。
例如:
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',它会成功返回选择,但如果我打印它将返回' Appppple'而不是Apple'。它打印第一个输入而不是满足if语句的输入。
答案 0 :(得分:2)
最简单的解决方法是从递归调用返回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())
目前,任何递归调用的返回值都将被丢弃,并且在第一次迭代中输入的值将被存储并在所有情况下返回。