简体   繁体   中英

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). 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 .

You should be better using if ((x % 2) == 0 and (x % 3) == 0) : print("2, 3: ", x) on that line.

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 )

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 .

As per Rajesh Kumar's suggestion you could do if x % 6 == 0: # ... or 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 = 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 (x % 3)

the two expressions in brackets return booleans that you finally evaluate using 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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