why does my code multiply 2 times instead of one

Question:

My code should verify if a number is even, if it is, it prints the number multiplied by 2, if it isn’t, it should print the number multiplied by 3, but just doesn’t work.

m = int(input())
for i in range(m):
    n = int(input())
    n*=2 if n%2==0 else n*3
    print(n)

When i try this input:

3
1
2
3

It returns:

3
4
**27** <- ?
Asked By: noobprogrammer

||

Answers:

n *= 2 if n % 2 == 0 else n * 3

means

n *= (2 if n % 2 == 0 else n * 3)

which means

if n % 2 == 0:
    n = n * 2
else:
    n = n * n * 3

You meant to write

n *= 2 if n % 2 == 0 else 3
Answered By: DeepSpace
n*=2 if n%2==0 else n*3

Operator precedence.

This statement is interpreted as

n *= (2 if n%2==0 else n*3)

And for input 3, n%2==0 is not true, so the statement becomes

n *= 9

Which is 27.

Answered By: John Gordon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.