繁体   English   中英

Python:打印x和y可除范围内的所有数字

[英]Python: Print all numbers in range divisible by x and y

我正在尝试打印1-100范围内所有可以被x和y整除的数字(即2 nad 3)。 现在我有

for x in range(0, 101):
    if x % (2 and 3) == 0: print("2, 3: ", x)
    elif x % 2 == 0: print("2: ", x)
    elif x % 3 == 0: print("3: ", x)

但这不准确,有什么建议吗?

(2 and 3)值为3 ,这就是为什么您永远不会看到条件elif x % 3 == 0被执行的原因,请注意print("3: ", x)代码输出中没有print("3: ", x) ,因为它已经if x % (2 and 3) == 0进入条件。

您最好在该行上使用if ((x % 2) == 0 and (x % 3) == 0) : print("2, 3: ", x)

它不准确的原因是通过编写x % (2 and 3) python正在解释(2和3)。( https://docs.python.org/2/reference/expressions.html

python(2和3)中的值将返回3,因为这两个值都是“ truthy”,并且当两项均为True时,python中的AND比较运算符将返回最后一个值。

根据Rajesh Kumar的建议, if x % 6 == 0: # ...if x % 2 == 0 and x % 3 == 0: # More verbose...

如果您必须用数字xy进行除数,则可以这样看:如果用除数x或除数y进行除法后还剩下一些余数,则当前考虑到的数字toDivide不是您要查找的数字因为,因为您想要一个数字,而任何一个部门都不会导致休息。

x = 2
y = 3
for toDivide in range(1, 101):
    # can't divide by x and y
    if toDivide%x and toDivide%y:
        continue
    print((str(x)+", "+str(y) if not toDivide%x and not toDivide%y else (str(x) if not toDivide%x else str(y)))+":"+str(toDivide))

编辑:找到并解决了代码错误

if x % (2 and 3) == 0则首先计算(2和3)的值,则应首先检查2除数,然后再检查3。

if (x % 2) and (x % 3)

方括号中的两个表达式返回布尔值,您最终将使用and对其进行求值。

更正:

for x in range(0, 101):
    if (x % 2) and (x % 3): 
        print("2, 3: ", x)
    elif x % 2 == 0: 
        print("2: ", x)
    elif x % 3 == 0: 
        print("3: ", x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM