Python Bibliotheca
Python resources for teachers and students.

Validating user input

An important part of making sure your program is as robust as possible is checking the user's input to make sure they've entered the right sort of information. Here's a simple example that illustrates the concept. More advanced techniques can be done using exception handling.

The following program just asks the user to enter a positive one-digit number and keeps asking them until they do. For a slightly more complex example, see my guessing game.

def validNum(num):
    if num < 0:
        print "%s is not positive. Try again." % num
        return 0
    elif num > 9:
        print "%s has more than one digit. Try again." % num
        return 0
    else:
        return 1

def getInput():
    while 1:
        num = raw_input("Enter a positive one-digit integer: ")
        if validNum(int(num)):
            break
    print "You're right. %s is a positive one-digit integer." % num
    return

if __name__ == '__main__':
    getInput()

When you run the program, it looks like this:

Enter a positive one-digit integer: 10
10 has more than one digit. Try again.
Enter a positive one-digit integer: -8
-8 is not positive. Try again.
Enter a positive one-digit integer: 5
You're right. 5 is a positive one-digit integer.

[ Copyright 2005, Tim Wilson ]

Comments, questions, or suggestions? Email the webmaster