我如何确定整数是2的倍数而不是3的倍数打印“<myint>仅是2的倍数”呢?使用python

2024-04-16 08:00:47 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
2条回答

做什么呢

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

其中%是模运算符,用左手操作数除以右手操作数并返回余数。因此,如果余数等于0,则左操作数是右操作数的倍数。你知道吗

因此

your_number%2 == 0如果your_number是2的倍数,则返回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")

你可以这样做:

#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")

两者工作原理相同

相关问题 更多 >