You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用if语句判断数字输入是否为空?解决Python ValueError报错

问题解决:空输入导致的ValueError及处理方案

错误原因

直接将input()的返回值转为float时,若用户未输入任何内容,得到的是空字符串"",而空字符串无法被转换为浮点数,因此触发ValueError: could not convert string to float: ''。

修正方案

先获取原始输入字符串,判断是否为空后再进行类型转换,同时可添加异常处理应对非数字输入:

import random

# 先获取原始输入字符串,不立即转换类型
speed_input = input("Which was the speed of the vehicle in that moment? ")

trafficTicket = 0

if speed_input == "": 
    print("The speed was not informed. ")
    randomNumber = random.randint(1, 120)
    random_traffic_ticket_value = randomNumber * 7
    print(f"The value of the traffic ticket in this situation is going to be {random_traffic_ticket_value} dollars. ")
else:
    # 尝试转换为浮点数,处理非数字输入的情况
    try:
        speed = float(speed_input)
        if speed < 30:
            print("The vehicle's speed is very low, tell the driver to change hands. ")
        elif speed > 90:
            trafficTicketValue = speed - 90
            print(f"Due to speed above the permitted speed, the driver must receive a traffic ticket worth {trafficTicketValue * 7} dollars. ")
        else:
            # 补充速度合规的提示(可选)
            print("The vehicle's speed is within the permitted range.")
    except ValueError:
        print("Invalid input. Please enter a valid number for speed.")

关键改进点

  • 先判断输入是否为空,避免空字符串转浮点数的错误
  • 使用try-except捕获非数字输入的异常,提升代码健壮性
  • 将独立if改为elif结构,让逻辑分支更清晰

内容的提问来源于stack exchange,提问作者Jorgityo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:06:05