在Python中验证用户输入的字符串

1 投票
6 回答
3242 浏览
提问于 2025-04-17 20:24

这是我在学习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”或数字,就应该提示他们:“抱歉,‘five’不是有效的输入,请再试一次。”然后再让用户输入一次。我刚开始学习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

6 个回答

0
if cost == 'q':
    break
else:
    try:
        totalCost += int(cost)
    except ValueError:
        print "Only Integers accepted"

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

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
4
if cost == 'q':
    break
else:
    try:
        totalCost += int(cost)
    except ValueError:
        print "Invalid Input"

这段代码会检查输入的内容是不是一个整数。如果是整数,它就会停止执行。如果不是整数,它会打印“无效输入”,然后重新回到输入的地方。希望这对你有帮助 :)

撰写回答