[英]Python: Print all numbers in range divisible by x and y
I'm trying to print all numbers in range 1-100 that are divisible by x and y (ie. 2 nad 3). 我正在尝试打印1-100范围内所有可以被x和y整除的数字(即2 nad 3)。 For now i have 现在我有
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)
But it is not accurate, any suggestions? 但这不准确,有什么建议吗?
(2 and 3)
evaluates to 3
, that's why you never see the condition elif x % 3 == 0
being executed, notice there's no print("3: ", x)
in the output of your code, because it'd already fallen into the condition if x % (2 and 3) == 0
. (2 and 3)
值为3
,这就是为什么您永远不会看到条件elif x % 3 == 0
被执行的原因,请注意print("3: ", x)
代码输出中没有print("3: ", x)
,因为它已经if x % (2 and 3) == 0
进入条件。
You should be better using if ((x % 2) == 0 and (x % 3) == 0) : print("2, 3: ", x)
on that line. 您最好在该行上使用if ((x % 2) == 0 and (x % 3) == 0) : print("2, 3: ", x)
。
The reason it is not accurate is by writing x % (2 and 3)
python is interpreting (2 and 3).( https://docs.python.org/2/reference/expressions.html ) 它不准确的原因是通过编写x % (2 and 3)
python正在解释(2和3)。( https://docs.python.org/2/reference/expressions.html )
in python (2 and 3) would return 3 because both values are "truthy" and the AND comparison operator in python will return the last value when both items are True
. python(2和3)中的值将返回3,因为这两个值都是“ truthy”,并且当两项均为True
时,python中的AND比较运算符将返回最后一个值。
As per Rajesh Kumar's suggestion you could do if x % 6 == 0: # ...
or if x % 2 == 0 and x % 3 == 0: # More verbose...
根据Rajesh Kumar的建议, if x % 6 == 0: # ...
或if x % 2 == 0 and x % 3 == 0: # More verbose...
If you have a number that hast to be dividable by number x
and number y
you can look at it like: If some rest is left after a division with divisor x
or divisor y
, the currently considered number toDivide
is not the number you are looking for, because you want numbers where neither of the devisions results in a rest. 如果您必须用数字x
和y
进行除数,则可以这样看:如果用除数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))
edit: found and resolved the code-error 编辑:找到并解决了代码错误
In if x % (2 and 3) == 0
the value of (2 and 3) is evaluated first, you should first check divisibility by 2 then by 3. ie if x % (2 and 3) == 0
则首先计算(2和3)的值,则应首先检查2除数,然后再检查3。
if (x % 2) and (x % 3)
the two expressions in brackets return booleans that you finally evaluate using and
. 方括号中的两个表达式返回布尔值,您最终将使用and
对其进行求值。
corrected: 更正:
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.