【问题标题】:How would I go about determining if an integer is a multiple of 2 but not a multiple of 3 print ‘<myint > is a multiple of 2 only.’ ? Using python [duplicate]我将如何确定一个整数是否是 2 的倍数但不是 3 的倍数 print ‘<myint > is a multiple of 2 only.’ ?使用 python [重复]
【发布时间】:2025-12-30 23:45:18
【问题描述】:

我将如何确定一个整数是否是 2 的倍数但不是 3 的倍数 print' is a multiple of 2 only.' ?使用python。

if myint%2: 
    print(str(myint), "is a multiple of 2 only")

如何让它输出“但不是 3 的倍数”

【问题讨论】:

  • 这是 FizzBu​​zz。它很受欢迎。请谷歌一下。

标签: python python-2.7 python-3.x if-statement boolean


【解决方案1】:

怎么办

your_number%2 == 0 and your_number%3 != 0

其中% 是取模运算符,将左侧操作数除以右侧操作数并返回余数。所以如果余数等于0,左操作数是右操作数的倍数。

这样

如果your_number 是 2 的倍数,your_number%2 == 0 返回 True

如果your_number 不是 3 的倍数,your_number%3 != 0 返回 True

为了给你一个完整的答案,你需要的是:

if myint%2 == 0 and myintr%3 != 0:
    print(str(myint), "is a multiple of 2 and not a multiple of 3")

【讨论】:

    【解决方案2】:

    你可以这样做:

    #first checks if myint / 2 doesn't has a reminder
    #then checks if myint / 3 has a reminder
    if not myint % 2 and myint % 3: 
        print(myint,"is a multiple of 2 only")
    

    或者如果你愿意:

    if myint % 2 == 0 and myint % 3 != 0: 
        print(myint,"is a multiple of 2 only")
    

    两者的工作原理相同

    【讨论】: