2017-08-21 43 views
1

我無法返回列表選項。從列表中選出一個選項

例如:

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語句的輸入。

+1

它將始終返回第一次嘗試的值,但不捕獲遞歸調用的返回值。爲了解決這個問題,從遞歸調用返回到'Choose_Fruit',例如'返回Choose_Fruit()'。除此之外,有更好的方法來實現你想要看到[這裏](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) 。 –

+1

你正在拋棄'Choose_Fruit()'的結果 –

回答

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()) 

從任何遞歸調用當前的返回值被丟棄,並在第一次迭代的輸入值存儲在所有情況下返回。

相關問題