Checking user input python

user2166941 picture user2166941 · Mar 25, 2013 · Viewed 14.3k times · Source

In my inputCheck function when the users input is passed through after being checked wether is an acceptable input should be confirmed by the print message and then run another function - however it doesn't do that and I cant figure out why - Would you be able to advise on how to solve the problem? Many thanks!

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

Answer

rainer picture rainer · Mar 25, 2013

You convert the user's input to a string (str(input('What ...'))) but compare it to integers in inputCheck. Since there is no else path in inputCheck, nothing happens when you enter a "valid" choice.

Also, if you're using Python 2, using input is not what you want, raw_input is the way to go (see, for example What's the difference between raw_input() and input() in python3.x?).

Other than that, recursively calling menuChoice whenever the user enters an illegal choice is quite probably a bad idea: enter an illegal choice a few hundred or thousand times and your program will crash (apart from waste a lot of memory). You should put the code in a loop:

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