I have searched google, but found nothing, I'm not even sure if this is what you call it. But in my program I am writing, if someone hits enter by mistake without entering anything, it errors, is there a way to avoid that?

Another error that happens is if the program is expecting a number and gets a letter.

Another error that happens is if the program is expecting a number and gets a letter.

if input_string.isdigit():
   do_something()
else :
   print "Enter a number"

if someone hits enter by mistake without entering anything, it errors, is there a way to avoid that?

if (input_string) and len(input_string) > 0 :
## -----or
try :
   input_str = raw_input( "Enter a Number --> " )
except :
   print "No number entered"
## -----or the old stand by
input_str = ""
while (len(input_str) < 1 )  or (not input_str.isdigit() ):
   input_str = raw_input( "Enter a Number --> " )

could someone be kind enough to elaborate on that? I'm sorry but to tell you the truth I just don't understand what any of that does... I get the whole try and except part, but thats it.

Well, in general, you should validate your input. What that means is making mathematically sure that the user enters a correct something, or else the program prints an error and continues on with life. That's what the first code snippet above does: if the user didn't type a (non-negative!) integer, he gets an error.

A more general way of validating the input is to let Python do it for you! If you try to convert a non-integer to an integer, you get a ValueError exception thrown. The second snippet of code above shows how to catch the exception and avoid having your program break.

Jeff

Here's my stab at a quick tutorial:

Validating Input

Any time your program receives input from a device, it needs to check whether the input is valid. By far, the two most common points for input are

(1) When the user types something at the keyboard, and
(2) When data is read from a file.

If your program fails to check the input for validity, then your program runs the risk of crashing, which can lead to the user being frustrated at his hard work going down the tubes and can even become an entry point for hackers (not so much in Python I think, but very true in C).

Here's an example:

(after two hours of game play ... )
What is your name? King Arthur of Camelot
What is your quest? To seek the Holy Grail
What is your favorite number? Three

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in -toplevel-
    a = int(raw_input("What is your favorite number? "))
ValueError: invalid literal for int(): Three

>>> @$#@$#$#%^%

How do you validate input?

First, Decide what the input should be. There are two things to consider: type and range. If your program is expecting a certain data type -- say, an integer -- then nothing else should be allowed. If the integer must be non-negative, then negatives should be verboten.

Second, at the point of input, verify that the input has the right type and range. This can happen either by using a try-except clause, or by manual checking, or both together

try:
    number = int(raw_input("Enter an integer between 0 and 8: "))
except:
    print "Invalid input!"
    number = 0
if not 0 <= number <= 8:
    print "Your number is out of range!"
    number = 0

Two things are important features in the code above. First, the user is always given feedback if his input is invalid. This frees him from the tyranny of the blank screen. Second, when the input is invalid, the value of number is set to a default. The default value should be one that is compatible with the rest of your code.

Alternatively, if no default value is suitable, you can enclose your validation in a while loop:

while True:
    try:
         number = int(raw_input("Enter an integer between 0 and 8: "))
    except:
         print "Invalid input!"
    if not 0 <= number <= 8:
         print "Your number is out of range!"
     else:
        break

Here, if the number is an integer and in range, the break statement will get the user out of the loop. Else, he will be forced to try again.

To sum up: always check input from keyboard and disk to make sure it is valid. Use try-except and conditionals to perform the checks, and use default values and while loops to recover from input errors. And always, always give the user feedback when an error occurs.

Hope it helps,
Jeff

Comments
good tut for a beginner - ~s.o.s~

Pack it into a function then you can use it again and again:

def get_integer():
    '''loops until integer value is entered, then returns it'''
    while True:
        try:
            num = int(raw_input("Enter integer number: "))
            return num
        except ValueError:
            print "Please, enter integer number!"

# get integer value from the user
val = get_integer()
print val
This article has been dead for over six months. Start a new discussion instead.