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

Python输入非浮点数时如何返回“请输入有效数字”的报错提示?

代码修改方案

你可以通过try-except语句捕获ValueError异常实现输入合法性校验,为了避免重复写校验逻辑,建议先封装一个通用的浮点数输入函数,修改后的完整代码如下:

# 封装通用的合法浮点数输入函数
def get_valid_float(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("please input a valid number(请输入有效数字)")

if unknown == 'S':
    if units in ('si', 'Si'):  
        u = get_valid_float("Enter the initial velocity in m/s :")
        v = get_valid_float("Enter the acceleration in m/s : ")
        t = get_valid_float("Enter seconds : ")
    else:
        u = get_valid_float("Enter the initial velocity in yards/s :")
        v = get_valid_float("Enter the acceleration in yards/s : ")
        t = get_valid_float("Enter the time take in s : ")

    S = 0.5 * (u + v) * t
    print("S is " , S)

逻辑说明

  • 封装的get_valid_float函数会循环请求用户输入,直到获取到可正常转换为浮点数的内容为止,不会直接抛出异常终止程序
  • 异常触发时输出的提示文本完全符合你的需求
  • 原有位移计算的业务逻辑没有做任何修改,仅替换了输入获取的部分

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 09:15:04