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

Python数组处理求助:如何限制用户输入值不超过100

解决Python输入分数范围限制的问题

你的核心问题是没有在用户输入单个分数时即时验证范围,原代码最后检查avg1 >= 401的逻辑完全错误——单个分数超过100的话,avg1根本达不到401(比如输入101,其他三个0,avg1是(101*4)/4=101),所以这个检查起不到作用。

修正后的代码实现

mark = []
totMark1 = 0

# 设置课前活动数量及权重相关
pre_class_activity = 4
weight1 = pre_class_activity * 4

try:
    print(f"Please enter the marks you have obtained in the {pre_class_activity} pre-class activities (0-100): ")
    for i in range(pre_class_activity):
        # 获取输入并转换为整数
        score = int(input())
        # 验证输入范围:必须在0到100之间(包含边界)
        if not (0 <= score <= 100):
            print(f"Error: Score cannot exceed 100 or be negative. Try again.")
            quit()
        # 验证通过后存入数组
        mark.append(score)
    
    # 计算总分和平均分(将平均分计算移到循环外,避免重复计算)
    for score in mark:
        totMark1 += score * 4
    avg1 = totMark1 / pre_class_activity

    # 可选:最终再做一次整体验证(防止逻辑漏洞)
    if avg1 > 400:
        print("Error: Total average exceeds 100% limit.")
        quit()

    # 这里可以添加后续的逻辑,比如打印结果
    print(f"Total weighted score: {totMark1}")
    print(f"Average weighted score: {avg1}")

except ValueError:
    # 处理用户输入非数字的情况
    print("Error: Please enter valid numeric values.")
    quit()

关键修改说明

  • 即时输入验证:在每次获取用户输入后,立刻检查分数是否在0-100区间内,不符合则直接提示错误并退出,避免无效数据进入数组。
  • 修正平均分计算位置:把avg1的计算移到循环外部,只在所有分数累加完成后计算一次,原代码在循环内每次计算属于冗余操作。
  • 添加非数字输入处理:用try-except捕获ValueError,处理用户输入非整数的情况,增强代码健壮性。
  • 调整最终验证逻辑:如果所有分数都合法,avg1最大为(100*4*4)/4=400,所以判断avg1>400即可检测逻辑漏洞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:10:31