从Lis中返回所选选项

2024-05-03 11:23:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在返回列表选项时遇到问题

例如:

 Fruits = {
     'Apple': Apple, 'Banana': Banana, 'Orange': Orange}

 def Choose_Fruit():
   Choice = input('Choose a fruit: ')
   if Choice not in Fruits:
     Choose_Fruit()
   return Choice

如果我输入'Apppple',它将迫使我再次选择。如果我输入'Apple',它将成功返回选项,但如果我要打印,它将返回'apppple',而不是'Apple'。它打印第一个输入,而不是满足if语句的输入


Tags: inapple列表inputifdef选项not
1条回答
网友
1楼 · 发布于 2024-05-03 11:23:27

最简单的修复方法是从对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())

目前,任何递归调用的返回值都会被丢弃,并且在所有情况下都会存储并返回第一次迭代中输入的值

相关问题 更多 >