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

带固定输入尝试次数的Python奇偶判断程序问题排查

问题解决:Python输入处理脚本的两个bug修复

问题原因分析

  1. 输入0未终止脚本:原代码中输入0时仅用break跳出了内层的次数循环,外层的错误尝试次数循环仍会继续执行,导致脚本无法完全终止。
  2. 错误打印"Sorry, too many attempts!":原代码中该提示是独立于循环的语句,无论用户是否完成10次有效输入,只要外层循环结束就会触发判断,导致不符合预期的输出。

修正后的代码

attempt = 0
max_attempts = 5
i = 0
i_max = 10

while attempt < max_attempts:
    try:
        while i < i_max:
            number = int(input('Please type in a positive integer; 0 to quit: '))
            if number == 0:
                print('All done!')
                exit()  # 直接终止整个脚本
            if number < 0:
                print('Please type in a positive number.')
                continue  # 不消耗输入计数,重新输入
            # 判断数字奇偶性
            if number % 2 == 0:
                print(f"The number {number} is even.")
            else:
                print(f"The number {number} is odd.")
            i += 1
            remaining = i_max - i
            print(f'Only {remaining} numbers left.' if remaining > 0 else 'All 10 inputs completed!')
        # 完成10次有效输入后,跳出外层循环
        break
    except ValueError:
        attempt += 1
        remaining_attempts = max_attempts - attempt
        print(f'Wrong input, {remaining_attempts} attempts left' if remaining_attempts > 0 else 'Wrong input, no attempts left')
# 仅当错误尝试次数耗尽时打印提示
if attempt == max_attempts:
    print('Sorry, too many attempts!')

关键修改点

  1. 输入0直接终止:用exit()替代单纯的break,确保输入0后脚本立即停止运行。
  2. 修正尝试次数计数逻辑:将attempt += 1移到except块内,只有输入错误时才消耗尝试次数,原代码的计数逻辑存在错误。
  3. 负数输入不消耗次数:添加continue语句,输入负数时不减少剩余的有效输入次数,让用户重新输入。
  4. 避免多余提示:完成10次有效输入后,通过break跳出外层循环,此时attempt不会达到max_attempts,不会触发最后的错误提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:10:32