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

能否通过try-except返回指定代码行,仅重新输入错误的矩形参数项?

实现方案

你可以把每个输入的校验逻辑单独抽成一个复用函数,每个输入项独立做异常捕获和重试,这样某一项输入错误时只会重试当前项,不会影响已经输入完成的内容,同时还修正了原代码中面积计算逻辑缩进错误的问题。

完整修改后代码

from fractions import Fraction

# 封装通用的数值输入校验函数
def get_valid_numeric_input(prompt):
    while True:
        try:
            return abs(float(Fraction(input(prompt))))
        except:
            print("please enter numeric values, try again:")

def Calc():
    Length1 = get_valid_numeric_input("First Rectangle Length:\n")
    Width1 = get_valid_numeric_input("First Rectangle Width:\n")
    Length2 = get_valid_numeric_input("Second Rectangle Length:\n")
    Width2 = get_valid_numeric_input("Second Rectangle Width:\n")
    
    RECTANGLE1 = Length1 * Width1
    RECTANGLE2 = Length2 * Width2

    if RECTANGLE1 > RECTANGLE2 :
        print (f"The First Rectangle Is Bigger! It's Area Is:\n{RECTANGLE1}")
    elif RECTANGLE1 == RECTANGLE2 :
        print (f"The Rectangles Are The Same! Their Area Is:\n{RECTANGLE1}")
    else :
        print (f"The Second Rectangle Is Bigger! It's Area Is:\n{RECTANGLE2}")

# 调用函数运行
Calc()

核心说明

  • 封装的get_valid_numeric_input函数接收提示文本作为参数,内部用无限循环,只有输入合法数值才会返回结果,否则一直停在当前输入步骤
  • 每个输入项独立调用该函数,相互不影响,比如输入Length2时出错只会重复要求输入第二个矩形的长度,不会重新询问已经输入完成的第一个矩形的长宽
  • 原代码中未使用的math库可以直接删除,不影响功能运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:00:01