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

Python圆柱体积计算器:输入非法值时如何重启循环?

圆柱体积计算器的循环修正方案

你的代码主要有三个问题:

  1. finally块会强制执行,哪怕输入负数还没完成所有输入,就会去计算体积,导致未定义变量报错
  2. 输入负数后没有触发循环重启,无法回到输入起始位置
  3. 没处理非数字输入的情况,输入字母会直接崩溃

下面是修正后的代码,完全符合你的需求:

while True:
    try:
        height = float(input("Enter the height of the cylinder. "))
        if height < 0:
            print("Only enter positive numbers.")
            continue  # 直接回到循环开头,重新输入
        
        radius = float(input("Enter the radius of the cylinder. "))
        if radius < 0:
            print("Only enter positive numbers.")
            continue  # 回到循环开头,重新输入
        
        # 所有输入合法时才计算并输出体积
        volume = height * 3.14159 * radius ** 2
        print(f"The volume of the cylinder is {volume} units")
    except ValueError:
        # 捕获非数字输入的异常,提示用户输入有效数字
        print("Please enter a valid number.")

关键修改说明:

  • 移除了finally块,把体积计算逻辑放在所有输入验证通过之后,只有合法输入才会执行这部分
  • 每次检测到负数输入时,用continue直接跳回循环起始位置,重新开始输入流程
  • 增加except ValueError捕获非数字输入的异常,避免程序崩溃,同时给出明确提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:55:29