如何限制输入,以便只使用某些字母或数字?(Python)

如何限制输入,以便只使用某些字母或数字?(Python),python,loops,limit,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 le

初学者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
bill\u amt=True
而账单金额:
账单金额=浮动(输入('首先,您的餐费是多少?(请不要使用“$”:'))

如果bill_amt这样的事情会奏效

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
bill\u amt=True
而账单金额:
尝试:
账单金额=浮动(输入('首先,您的餐费是多少?(请不要使用“$”:'))
除值错误外:
打印('请只输入一个数字')
持续

if bill_amt
float
如果该数字不是数字,则只会抛出一个错误。刚开始我想建议一个正则表达式,但是对于这个简单的问题,popovitsji的答案非常有效。抛开
bill\u amt=True/False
的东西和
x=float(bill\u amt)
的东西,因为它不再需要了,但是我衷心地赞成让
float()
为您进行测试。此外,您应该捕获正在处理的错误,而不是所有错误。在这种情况下,
ValueError