用户输入的是q么python_在python中验证用户输入字符串

这是我从事过的一本书中的一些代码,因为我是Python的新手....这部分是应该的

totalCost = 0

print 'Welcome to the receipt program!'

while True:

cost = raw_input("Enter the value for the seat ['q' to quit]: ")

if cost == 'q':

break

else:

totalCost += int(cost)

print '*****'

print 'Total: $', totalCost

share|edit

answered 8 hours ago

我的困境是....我需要验证输入是什么...所以如果用户输入一个字符串(比如单词'five'而不是数字)而不是q或数字它告诉他们“我是对不起,但'五'无效 . 请再试一次.....然后它会再次提示用户输入 . 我是Python的新手并且在这个简单的问题上绞尽脑汁

UPDATE** 由于我没有足够的学分来添加我自己的问题的答案所以日志我在这里发布....

Thank you everyone for your help. I got it to work!!! I guess it's going to take me a little time to get use to loops using If/elif/else and while loops.

This is what I finally did

total = 0.0

print 'Welcome to the receipt program!'

while True:

cost = raw_input("Enter the value for the seat ['q' to quit]: ")

if cost == 'q':

break

elif not cost.isdigit():

print "I'm sorry, but {} isn't valid.".format(cost)

else:

total += float(cost)

print '*****'

print 'Total: $', total

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值