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

Python实现双条件while循环:处理空输入与数值<1的校验问题

Python投资金额输入校验解决方案

原代码在用户直接回车输入空内容时会抛出ValueError: could not convert string to float,同时需要校验输入数值不小于1,以下是修复并优化后的代码:

def obtener_monto_inversion(numero_inversionista):
    while True:
        entrada = input(f"Indique el monto a invertir por el inversionista {numero_inversionista} ")
        # 处理空输入
        if not entrada.strip():
            print("No puede dejar el campo vacío, ingrese un valor válido")
            continue
        try:
            monto = float(entrada)
            # 校验金额需大于等于1
            if monto >= 1:
                return monto
            else:
                print("El aporte del inversionista debe ser mayor o igual a 1")
        except ValueError:
            print("Ingrese un número válido")

# 获取三位投资者的投资金额
Inv1 = obtener_monto_inversion(1)
Inv2 = obtener_monto_inversion(2)
Inv3 = obtener_monto_inversion(3)

# 计算总资本及各投资者占比
Capital = Inv1 + Inv2 + Inv3
Rep1 = (Inv1 * 100) / Capital
Rep2 = (Inv2 * 100) / Capital
Rep3 = (Inv3 * 100) / Capital

# 格式化输出结果
print(f"El capital aportado por el inversionista 1 equivale al {Rep1:.2f}% del capital total")
print(f"El capital aportado por el inversionista 2 equivale al {Rep2:.2f}% del capital total")
print(f"El capital aportado por el inversionista 3 equivale al {Rep3:.2f}% del capital total")

关键修复说明:

  • 空输入拦截:先检查输入字符串是否为空(去除首尾空格后判断),直接提示用户重新输入,避免后续类型转换报错。
  • 异常处理:用try-except捕获非数字输入导致的ValueError,确保程序不会崩溃,同时提示用户输入有效数字。
  • 循环校验逻辑:通过while True实现持续输入,直到用户输入符合要求的金额(≥1的有效数字)才退出循环。
  • 代码复用:将重复的输入校验逻辑封装成函数,减少冗余代码,后续若需修改校验规则只需调整函数即可。
  • 结果美化:用字符串格式化保留两位小数,让占比结果更易读。

内容的提问来源于stack exchange,提问作者José Flores

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:13:09