2013-03-25 171 views
-6

在我的inputCheck函數中,當用戶輸入被檢查通過後,它是一個可接受的輸入,應該由打印消息確認,然後運行另一個函數 - 但它不這樣做,我不能爲什麼 - 你能告訴如何解決問題?非常感謝!檢查用戶輸入python

def main(): 
    print('WELCOME TO THE WULFULGASTER ENCRYPTOR 9000') 
    print('==========================================') 
    print('Choose an option...') 
    print('1. Enter text to Encrypt') 
    print('2. Encrypt text entered') 
    print('3. Display Encrypted Text!') 
    menuChoice() 

def menuChoice(): 
    valid = ['1','2','3'] 
    userChoice = str(input('What Would You Like To Do? ')) 
    if userChoice in valid: 
     inputCheck(userChoice) 
    else: 
     print('Sorry But You Didnt Choose an available option... Try Again') 
     menuChoice() 

def inputCheck(userChoice): 
    if userChoice == 1: 
     print('You Have Chosen to Enter Text to Encrypt!') 
     enterText() 
    if userChoice == 2: 
     print('You Have Chosen to Encypt Entered Text!') 
     encryptText() 
    if userChoice == 3: 
     print('You Have Chosen to Display Encypted Text!') 
     displayText() 

def enterText(): 
    print('Enter Text') 

def encryptText(): 
    print('Encrypt Text') 

def displayText(): 
    print('Display Text') 


main() 
+1

我不明白你的問題。 – wRAR 2013-03-25 18:37:53

+0

讓我編輯問題抱歉 – user2166941 2013-03-25 18:39:46

回答

3

你用戶的輸入轉換爲字符串(str(input('What ...'))),但在inputCheck把它比作整數。由於inputCheck中沒有else路徑,因此當您輸入「有效」選項時沒有任何反應。另外,如果你使用的是Python 2,使用input不是你想要的,raw_input是要走的路(例如參見What's the difference between raw_input() and input() in python3.x?)。

除此之外,每當用戶輸入非法選擇時遞歸地調用menuChoice可能是一個糟糕的主意:幾百次或幾千次輸入非法選擇,並且程序崩潰(除了浪費大量內存外)。你應該把代碼放在一個循環中:

while True: 
    userChoice = str(raw_input('What Would You Like To Do? ')) 
    if userChoice in valid: 
     inputCheck(userChoice) 
     break 
    else: 
     print('Sorry But You Didnt Choose an available option... Try Again') 
+0

謝謝!我會代表答覆,但我沒有足夠的自己來這樣做! – user2166941 2013-03-25 18:44:54

+0

你可以隨時接受答案;) – rainer 2013-03-25 18:51:06