I am working my way through some Python tutorials one of the things that keeps coming up is user input and i just wanted to check that i am validating it correctly and not going about it the long way around.
I have written the code below and only need to ask for the day month and year but if i needed to start asking for address phone number name etc etc this would grow and grow is that normal?
def get_input( i ):
while True:
# We are checking the day
if i == 'd':
try:
day = int( raw_input( "Please Enter the day: " ) )
# If the day is not in range reprint
if day > 0 and day < 32:
#Need to account for short months at some point
return day
else:
print 'it has to be between 1 and 31'
except ( ValueError ):
print "It has to be a number!"
elif i == 'm':
# We are checking the month
month = raw_input( 'Please enter ' +
'in words the month: '
).strip().lower()
if month in months: # use the dict we created
return month
else:
print 'Please check you spelling!'
elif i == 'y':
# Now the year
try:
year = int( raw_input( "Please Enter the year" +
"pad with 0's if needed: " ) )
#make we have enough digits and a positive
if year > 0 and len( year ) == 4:
return year
except ( ValueError, TypeError ):
print "It has to be a four digit number!"
Why don’t you just have the user input the whole date in one go, and try it out to validate it?
This will catch errors like
29/2/2011but accept valid inputs like29/2/2012.If you’d like to accept several formats, just make a list of the format strings you want to accept and try them out one after another on the input, until you find one that works. But watch out for the problem of usage overloading.
For validating phone numbers I’d just go for a regexp. If you’ve never used regexps before there’s a nice python regexp howto here. Addresses are very free form, so I don’t think I’d bother validating them beyond restricting the length and doing basic security checking, especially if you’re accepting international addresses.
But in general, if there’s a python module for it you should just try to create an instance based on the input and catch the errors, like I do for the time module in the above example.
Don’t even try to validate names. Why not? Look at this article. 🙂