2016-04-14 47 views
1
def confirm_choice(): 
    confirm = input("[c]Confirm or [v]Void: ") 
    if confirm != 'c' and confirm != 'v': 
     print("\n Invalid Option. Please Enter a Valid Option.") 
     confirm_choice() 
    print (confirm) 
    return confirm 

例如,如果輸入字符'k'後跟有效輸入'c',該函數將打印輸入'c'和'k'在python中創建確認功能

輸出:

c 
k 

如何用上述程序被改變,使得它僅返回任一「C」或「v'and重複功能,如果輸入是無效的。

+3

的可能的複製[?我如何使用嘗試..除或IF ... ELSE驗證用戶輸入(http://stackoverflow.com/questions/5557937 /怎麼辦,我使用的試 - 除了有或的if-else對驗證用戶輸入) – jeremycg

回答

3

你忘了之後遞歸調用confirm_choice()返回,所以它掉下來的,如果塊的和執行

print (confirm) 
return confirm 

將打印第一個無效的輸入。

def confirm_choice(): 
    confirm = input("[c]Confirm or [v]Void: ") 
    if confirm != 'c' and confirm != 'v': 
     print("\n Invalid Option. Please Enter a Valid Option.") 
     return confirm_choice() 
    print (confirm) 
    return confirm 

應該表現正確。

3

遞歸是不必要的;它更容易使用這個while循環:

while True: 
    confirm = input('[c]Confirm or [v]Void: ') 
    if confirm in ('c', 'v'): 
     return confirm 
    else: 
     print("\n Invalid Option. Please Enter a Valid Option.")