Skip to main content
 首页 » 编程设计

python之有没有更好的方法来检查输入是否为数字输入可以是 int 或 float

2025年05月04日14fff_TT

想知道是否有更好的方法来做到这一点。 Python 是我的第一门编程语言。

while True: 
    amount_per_month = raw_input('\nWhat is the monthly cost?\n==> ') 
    # seperate dollars and cents. 
    amount_list = amount_per_month.split(".") 
    # checking if int(str) is digit 
    if len(amount_list) == 1 and amount_list[0].isdigit() == True: 
        break 
    # checking if float(str) is digit 
    elif len(amount_list) == 2 and amount_list[0].isdigit() and amount_list[1].isdigit() == True: 
        break 
    else: 
        raw_input('Only enter digits 0 - 9.  Press Enter to try again.') 
        continue 

请您参考如下方法:

就试着让它成为一个float,如果不能转换就处理抛出的异常。

try: 
    amount_per_month = float( raw_input('What is the monthly cost?') ) 
except (ValueError, TypeError) as e: 
    pass # wasn't valid 

TypeError 在这里是多余的,但是如果转换是在其他 Python 对象(不仅仅是字符串)上进行的,那么就需要捕获诸如 float( [1, 2, 3] )。