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

Python「奇偶判断」小游戏逻辑错误排查求助

问题分析

  • 胜负判定逻辑缺失:原有代码仅判断了「结果为偶数且用户选偶数」的用户获胜场景,遗漏了「结果为奇数且用户选奇数」的用户获胜场景,因此用户选odd时无论结果是否匹配都会被判负。
  • 累加符号书写错误:原有代码的计分赋值写为=+,实际语义是将变量直接赋值为正1,而非在原有数值基础上累加1,正确的累加写法应为+=。

修正后完整代码

import random

options = ["odd", "even"]
user_wins = 0
comp_wins = 0

while True:
    user_answer = input("Choose odd or even. ").lower()
    if user_answer not in options:
        print("Try again.")
        quit()
    user_answer2 = input("Choose a number larger than zero. ")
    if user_answer2.isdigit():
        user_answer2 = int(user_answer2)
        if user_answer2 <= 0:
            print("Type a number larger than zero. ")
            quit()
    else:
        print("Type a number next time.")
        quit()
    comp_pick = random.randint(0, 10)
    if user_answer == "odd":
        print("Computer picked even and its number is", comp_pick)
    else:
        print("Computer picked odd and its number is", comp_pick)
    total = user_answer2 + comp_pick
    if total % 2 == 0:
        result = "even"
    else:
        result = "odd"
    # 修正胜负判断逻辑,覆盖奇偶两种匹配场景
    if result == user_answer:
        print("The result is", total, "You won!")
        user_wins += 1 # 修正累加符号
    else:
        print("The result is", total, "Computer won!")
        comp_wins += 1 # 修正累加符号
    print("Your score:", user_wins)
    print("Computer score:", comp_wins)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:18:01