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

如何实现输入RESTART时重启Python面积体积计算代码?

实现RESTART功能的修改方案

先修正原代码里的逻辑问题,再添加重启循环的功能:

原代码的几个问题

  • 条件判断写法错误:if z == 'Area' or 'area' 这种写法永远为真,因为非空字符串在布尔判断里是True,正确的写法应该是判断输入是否匹配大小写不同的关键词。
  • 退出条件同样有问题:a == 'CLOSE' or 'close' or 'Close' 逻辑不成立,会导致不管输入什么都会触发退出。

修改后的完整代码

while True:
    # 获取长宽输入,加异常处理避免非数字输入崩溃
    try:
        x = int(input("Type length: "))
        y = int(input("Type Width: "))
    except ValueError:
        print("请输入有效的数字!")
        continue

    print("IF you wanna find AREA Type Area")
    print("IF you wanna find VOLUME Type Volume")

    # 处理输入,转小写+去空格,兼容各种大小写输入
    z = input("What You wanna find: ").strip().lower()

    area = x * y
    volume = (x * 2) + (y * 2)  # 注:这个公式其实是矩形周长,若要算体积需要第三个维度(高度)

    if z == 'area':
        print("Area is ", area)
    elif z == 'volume':
        print("Volume is ", volume)
    else:
        print("Something Goes Wrong")

    print("You wanna find another value type RESTART")
    print("You wanna find another value type CLOSE")

    a = input().strip().lower()
    if a == 'close':
        break  # 退出循环,程序结束
    # 如果输入不是restart,提示后继续循环(相当于重启)
    elif a != 'restart':
        print("无效指令,程序将重新开始")

关键修改点

  • 循环包裹核心逻辑:用while True创建无限循环,只要用户不输入CLOSE,就会重复执行计算流程。输入RESTART时,循环自动回到开头;输入CLOSE时用break退出循环。
  • 输入兼容处理:用.strip().lower()统一处理用户输入,不管输入Area、AREA还是带空格的area,都能正确识别,不用写一堆或条件。
  • 异常防护:加了try-except捕获非数字输入的情况,避免程序直接崩溃,提示后重新开始输入。
  • 退出逻辑优化:用break替代exit(),更温和,符合Python的循环控制逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:40:41