[英]Sum of all numbers within a range without numbers divisible by x in python
[英]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...
如果您必須用數字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))
編輯:找到並解決了代碼錯誤
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.