如何限制输入只允许特定字母或数字?(Python)

0 投票
1 回答
971 浏览
提问于 2025-04-18 05:44

我是一个初学者,正在写一个小费计算器,它可以在给定的餐费上加上小费,但我遇到了一个问题。这里是我需要帮助的代码。

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 个回答

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

撰写回答