Reputation: 27
First :
a = int(input())
if a%4 == 0:
a += 1
if a%4 != 0:
a -= 1
print(a)
Second :
a = int(input())
b = a%4
if b == 0:
a += 1
if b != 0:
a -= 1
print(a)
Upvotes: 1
Views: 53
Reputation: 350345
The first will have possibly modified a
before the second if
condition is evaluated, and so behaves differently:
if a%4 == 0:
a += 1 # this influences the result of the next IF
if a%4 != 0:
a -= 1
In fact, in this particular case, if the first condition is true, then after 1 is added to a
, the second condition will also be true, and so a
gets 1 deducted from it again.
The second version first stores in b
the result needed for the conditions to work on the original input value, and only then performs the modification of a
, which is no longer playing a role in the if
conditions. There, it is guaranteed that only one of the two if
conditions is true.
However, most would just use else
, which removes this problem:
if a%4 == 0:
a += 1
else:
a -= 1
Upvotes: 8