如何限制输入,只使用某些字母或数字? (蟒蛇)

时间:2014-05-07 20:33:12

标签: python loops limit

初学者python用户!我正在写一个小费计算器,它会为给定的膳食量添加小费,但我遇到了问题。这是我需要帮助的代码。

bill_amt = True
while bill_amt:
    bill_amt = float(input('First, what was the price of your meal?(Please do not use signs such as "$"):'))
    if bill_amt <= 0: #or if bill_amt has letters or symbols
        print('Your meal wasn\'t $',bill_amt, '! Please try again.')
        bill_amt = True
    else:
        x = float(bill_amt)
        bill_amt = False

我希望能够添加if bill_amt <= 0:一个命令,该命令也会捕获符号(不包括句号。)和字母,这样如果您输入54.65美元或56.ad的价格,那么您将不得不输入正确的输入。谢谢,对不起,如果这是重复的! -Pottsy

1 个答案:

答案 0 :(得分:1)

这样的事情会起作用。

bill_amt = True
while bill_amt:
    try:
        bill_amt = float(input('First, what was the price of your meal?(Please do not use signs such as "$"):'))
    except ValueError:
        print('Please enter just a number')
        continue
    if bill_amt <= 0: #or if bill_amt has letters or symbols
        print('Your meal wasn\'t $',bill_amt, '! Please try again.')
        bill_amt = True
    else:
        x = float(bill_amt)
        bill_amt = False