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

使用while循环输入stop终止程序时出现int()转换错误的问题

问题解决:成绩等级循环判断程序修复

错误原因

直接把输入内容强制转成int,当输入"stop"时,字符串无法转换为整数,触发invalid literal for int() with base 10: 'stop'错误;另外原代码里marks == str.stop是无效写法,str没有stop这个属性。

修复方案

先获取原始输入字符串,先判断是否是"stop"来终止循环,再处理成绩的转换和等级判断,同时加入异常处理防止输入非数字非stop的内容导致报错。

修正后的完整代码

while True:
    user_input = input("Enter the marks (or type 'stop' to exit): ")
    # 先判断是否终止循环
    if user_input.lower() == 'stop':
        break
    # 尝试转换为整数并判断等级
    try:
        marks = int(user_input)
        print(f"输入的成绩:{marks}")
        if marks <= 40:
            print("Grade F")
        elif marks <= 50:
            print("Grade E")
        elif marks <= 70:
            print("Grade D")
        elif marks <= 80:
            print("Grade C")
        elif marks <= 90:
            print("Grade B")
        elif marks <= 100:
            print("Grade A")
        else:
            print("成绩超出范围,请输入0-100之间的数字")
    except ValueError:
        print("输入无效,请输入数字或'stop'")

代码说明

  • 先获取输入的原始字符串,用lower()兼容大小写的"stop"输入,满足条件直接跳出循环
  • 用try-except捕获输入非数字时的异常,避免程序崩溃
  • 新增了成绩超出0-100范围的提示,让程序逻辑更完整健壮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 21:06:06