如何在Python面积计算器代码中实现while循环?
给面积计算器添加while循环的解决方案
我们要实现的核心是让程序可以重复运行,直到用户主动选择退出。以下是修改后的完整代码及关键说明:
修改后的完整代码
def calculate_square_area(side: float): return side * side # 修正原代码中拼写错误:rectangele → rectangle def calculate_rectangle_area(length: float, width: float): return length * width def calculate_circle_area(radius: float): pi = 3.14 return pi * radius ** 2 def calculate_rhombus_area(p: float, q: float): return p * q / 2 def calculate_area(selection): area = 0 if selection == "S": side = input("输入边长:") area = calculate_square_area(float(side)) elif selection == "R": length = input("输入长度:") width = input("输入宽度:") area = calculate_rectangle_area(float(length), float(width)) elif selection == "C": radius = input("输入半径:") area = calculate_circle_area(float(radius)) elif selection == "H": p = input("输入对角线p:") q = input("输入对角线q:") area = calculate_rhombus_area(float(p), float(q)) else: print("无效选择") return area def get_shape_name(tag): shape = "未知图形" if tag == "S": shape = "正方形" elif tag == "R": shape = "长方形" elif tag == "C": shape = "圆形" elif tag == "H": shape = "菱形" return shape print(""" --------------- 面积计算器 --------------- """) # 核心while循环实现重复运行逻辑 while True: selection = input(""" 'S' - 正方形 'R' - 长方形 'C' - 圆形 'H' - 菱形 'Q' - 退出程序 请选择:""").strip().upper() # 退出循环的触发条件 if selection == "Q": print("程序已退出") break area = calculate_area(selection) # 仅在选择有效图形时输出结果 if selection in ["S", "R", "C", "H"]: print(f"{get_shape_name(selection)}的面积是:{area}\n")
关键修改说明
- 无限循环框架:用
while True创建循环体,代码会重复执行内部逻辑,直到遇到break语句终止。 - 退出选项:新增'Q'选项,用户输入后触发
break直接退出循环,结束程序。 - 输入容错优化:用
.strip().upper()处理用户输入,自动去除空格并转为大写,避免因输入小写、带空格导致的识别错误。 - 输出逻辑优化:只有当用户选择有效图形时才输出面积结果,避免无效选择时显示“未知图形的面积是0”的不合理提示。
内容的提问来源于stack exchange,提问作者Hunter Morriss
相关产品推荐
相关产品推荐

