Sav*_*avo 2 python validation user-input
我正在通过一些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!"
Run Code Online (Sandbox Code Playgroud)
为什么不让用户一次输入整个日期,并尝试验证它?
from time import strptime
def get_date():
while True:
date = raw_input("Please enter a date in DD/MM/YYYY format: ")
try:
parsed = strptime(date, "%d/%m/%Y")
except ValueError as e:
print "Could not parse date: {0}".format(e)
else:
return parsed[:3]
year, month, day = get_date()
Run Code Online (Sandbox Code Playgroud)
这将捕获错误,29/2/2011但接受有效的输入,如29/2/2012.
如果你想接受几种格式,只需要列出你想要接受的格式字符串,然后在输入中一个接一个地尝试它们,直到找到一个有效的格式.但请注意使用重载的问题.
为了验证电话号码,我只想进行正则表达式.如果你从来没有使用过regexp,那么这里有一个很好的python regexp howto .地址是非常自由的形式,所以我认为除了限制长度和进行基本的安全检查之外,我不打算验证它们,特别是如果你接受国际地址.
但一般来说,如果有一个python模块,你应该尝试创建一个基于输入的实例并捕获错误,就像我在上面的例子中为time模块做的那样.
甚至不尝试验证名称.为什么不?看看这篇文章.:)
| 归档时间: |
|
| 查看次数: |
11854 次 |
| 最近记录: |