Source code for read_valid_input

"""This code illustrates the reading of valid integer input
using a while loop and a break until a correct input is entered.

User either enters the correct input or the system assumes 0
is entered after three attempts.

"""

[docs]def read_input(): """This function reads an input from the user, and if it is not a valid integer, continues to prompt and ask for more. However, after three unsuccessful attempts, it assumes 0 is entered. """ attempts = 0 num = raw_input("Enter a number ==> ") while (True): ###the number is not a digit ## keep asking for a new value attempts += 1 if attempts >= 3: num = '0' print 'I assume you entered 0' break if num.is_digit(): break print "You did not enter a number" print "I wish you tried harder" num = raw_input("Enter a number ==> ") num = int(num) return num