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** <- ?
CodePudding user response:
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
CodePudding user response:
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.