Python圆柱体积计算器:输入非法值时如何重启循环?
圆柱体积计算器的循环修正方案
你的代码主要有三个问题:
finally块会强制执行,哪怕输入负数还没完成所有输入,就会去计算体积,导致未定义变量报错- 输入负数后没有触发循环重启,无法回到输入起始位置
- 没处理非数字输入的情况,输入字母会直接崩溃
下面是修正后的代码,完全符合你的需求:
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
相关产品推荐
相关产品推荐

