'Divisible by two given integers

x=[1,2,3,4,5,6]

for y in x:
    if y %2 == 0:
        print (y)
    elif y %3 == 0:
        print ("y")
    elif y %3 and y %2 ==0:
        print ("Divisible by 2 and 3!")
    else:
        print ("Odd number!")

I was trying to find out the even and odd numbers between 1 to 6. All worked out fine except the integer 6 where I need it to print out that the integer 6 is divisible by 2 and 3. How can I fix the error?



Solution 1:[1]

The test for divisible by 2 and 3 should come first, so for 6 you have y %3==0 and y %2 ==0 evaluated instead of y %2 == 0:

for y in x:
    if y % 3 == 0 and y % 2 == 0:
        print ("Divisible by 2 and 3!")
    elif y % 2 == 0:
        print (y)
    elif y % 3 == 0:
        print (y)
    else:
        print ("Odd number!")

Solution 2:[2]

There are two problems here: first of all, the condition should be:

elif y %3 == 0 and y %2 ==0:

Since there are two separate conditions. Next you need to move that check to the top, so:

for y in x:
    if y %3 == 0 and y %2 ==0:
        print ("Divisible by 2 and 3!")
    elif y %2 == 0:
        print (y)
    elif y %3 == 0:
        print ("y")
    else:
        print ("Odd number!")

Why? Because if a number is dividable by 2 and 3, it is also dividable by 2. So that means in your case it would have picked the first branch. By swapping the order it will first check if it is dividable by 2 and 3. If that is not the case - that is if at least one condition fails - it will check the remaining branches.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Moses Koledoye
Solution 2 Willem Van Onsem