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

如何让Python程序输入‘stop’时不触发ValueError异常提示?

解决方案

你的代码核心问题在于先将输入强制转为整数,再判断是否为"stop"——这时候输入"stop"会直接触发ValueError,而且整数类型永远不可能等于字符串"stop",导致停止逻辑完全失效。

修正思路:

  • 先获取原始输入字符串,优先判断是否为"stop",满足条件直接退出程序
  • 若不是"stop",再尝试将字符串转为整数,进行累加操作
  • 仅当输入既不是"stop"也不是有效整数时,才触发错误提示

修正后的代码:

from sys import exit

total_sum = 0

while True:
    print('to stop, write "stop"')
    user_input = input("Enter a number: ")
    # 先判断停止指令
    if user_input.lower() == "stop":  # 加lower()兼容大小写输入,可选
        print("the program has stopped")
        exit()
    # 再尝试转换为整数并累加
    try:
        num = int(user_input)
        total_sum += num
        print("the total number now is:", total_sum)
    except ValueError:
        print("please input a valid whole number or 'stop'")

关键改动说明:

  1. 将try块缩小到仅包含类型转换和累加操作,避免把停止判断也包裹进去
  2. 先处理"stop"的判断逻辑,确保输入"stop"时不会进入类型转换步骤
  3. 可选的lower()方法可以让用户输入"STOP""Stop"等也能触发停止,提升程序容错性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 01:19:53