python验证用户输入_用Python验证用户输入的正确方法

我正在学习一些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!"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值