我正在学习一些Python教程,其中经常涉及用户输入,我想确认我是否正确验证了它,而不是绕了一个长远的路。
我编写了下面的代码,只需要询问日期、月份和年份,但如果我需要开始询问地址、电话号码、姓名等等,那么这个代码将会变得越来越复杂,这正常吗?
我编写了下面的代码,只需要询问日期、月份和年份,但如果我需要开始询问地址、电话号码、姓名等等,那么这个代码将会变得越来越复杂,这正常吗?
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!"