我在返回列表选项时遇到问题。
例如:
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())
目前,任何递归调用的返回值都会被丢弃,并且在所有情况下都会存储并返回第一次迭代中输入的值。
关于python - 返回从列表中选择的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45806631/