【问题标题】:Return a Selected an Option out of a List从列表中返回选定的选项
【发布时间】:2018-01-30 02:10:26
【问题描述】:

我无法返回列表选项。

例如:

 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,例如return Choose_Fruit()。除此之外,还有更好的方法来实现你想要看到的here
  • 你正在丢弃Choose_Fruit()的结果

标签: python list if-statement return


【解决方案1】:

最简单的解决方法是从递归调用返回到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())

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    相关资源
    最近更新 更多