首页 文章

在python中验证用户输入字符串

提问于
浏览
1

这是我从事过的一本书中的一些代码,因为我是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

6 回答

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

    我还建议使用:

    if cost.lower() == 'q':
    

    如果它是一个资本“Q”仍然退出 .

  • 0
    if cost == 'q':
        break
    else:
        try:
            totalCost += int(cost)
        except ValueError:
            print "Invalid Input"
    

    这将查看输入是否为整数,如果是,则会中断 . 如果不是,它将打印“Invalid Input”并返回raw_input . 希望这可以帮助 :)

  • 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
    
  • 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?涵盖了这个特定情况(检查字符串中的数值)并且包含指向其他类似问题的链接 .

  • 4

    您可以使用以下方式投射输入:

    try:    
        float(q)
    except:
        # Not a Number
        print "Error"
    

    如果用户的输入只能是带点的整数,则可以使用q.isdigit()

相关问题