2013-03-25 118 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