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

Python实现两个整数奇偶性判断的代码逻辑异常咨询

问题原因

你的代码仅在num1为偶数的分支中判断了num2的奇偶性,当num1为奇数时,没有额外判断num2的奇偶就直接输出两个数都是奇数,这就是num1=5、num2=16时输出错误的原因。

修复后的代码

def q6():
    num1 = int(input("Enter One Number: "))
    num2 = int(input("Enter Second Number: "))
    
    if num1 % 2 == 0:
        if num2 % 2 == 0:
            print("两个数均为偶数")
        else:
            print("一个为偶数,另一个为奇数")
    else:
        # 补充num1为奇数时对num2的奇偶判断
        if num2 % 2 == 0:
            print("一个为偶数,另一个为奇数")
        else:
            print("两个数均为奇数")
q6()

更简洁的写法推荐

你也可以用平级判断减少嵌套层级,逻辑可读性更高:

def q6():
    num1 = int(input("Enter One Number: "))
    num2 = int(input("Enter Second Number: "))
    num1_is_even = num1 % 2 == 0
    num2_is_even = num2 % 2 == 0
    
    if num1_is_even and num2_is_even:
        print("两个数均为偶数")
    elif not num1_is_even and not num2_is_even:
        print("两个数均为奇数")
    else:
        print("一个为偶数,另一个为奇数")
q6()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:57:01