这是我从事过的一本书中的一些代码,因为我是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的新手,并且一直在绞尽脑汁解决这个简单的问题
*的 更新 ** 由于我没有足够的学分来为我自己的问题添加答案,因此我在这里发布了这个....
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
答案 0 :(得分:4)
if cost == 'q':
break
else:
try:
totalCost += int(cost)
except ValueError:
print "Invalid Input"
这将查看输入是否为整数,如果是,则会中断。如果不是,它将打印“Invalid Input”并返回raw_input。希望这会有所帮助:)
答案 1 :(得分:0)
你可能需要检查它是否是数字:
>>> '123'.isdigit()
True
这就像是:
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
elif cost.isdigit():
totalCost += int(cost)
else:
print('please enter integers.')
print '*****'
print 'Total: $', totalCost
答案 2 :(得分:0)
你已经大部分时间了。你有:
if cost == 'q':
break
else:
totalCost += int(cost)
因此可以在if
语句中添加另一个子句:
if cost == 'q':
break
elif not cost.isdigit():
print 'That is not a number; try again.'
else:
totalCost += int(cost)
How can i check if a String has a numeric value in it in Python?涵盖了这个特定情况(检查字符串中的数值),并链接到其他类似的问题。
答案 3 :(得分:0)
您可以使用以下方式投射输入:
try:
float(q)
except:
# Not a Number
print "Error"
如果用户的输入只能是带点的整数,则可以使用q.isdigit()
答案 4 :(得分:0)
if cost == 'q':
break
else:
try:
totalCost += int(cost)
except ValueError:
print "Only Integers accepted"
答案 5 :(得分:0)
try:
int(cost)
except ValueError:
print "Not an integer"
我还建议使用:
if cost.lower() == 'q':
如果它是大写字母“Q”,仍然会退出。