Home > Software design >  Why is classic if writing and inline if writing are not behaving the same way?
Why is classic if writing and inline if writing are not behaving the same way?

Time:10-29

I got this code

firstId = True
       
for x in [1,2,3,4,5]:
    firstId = False if firstId else print(str(x)  " "   str(firstId))
    
print ("What is happening here ???")

firstId = True
       
for x in [1,2,3,4,5]:
    if firstId: 
        firstId = False
    else:
        print(str(x)  " "   str(firstId))

And strangly i have this output

2 False
3 None
4 None
5 None
What is happening here ???
2 False
3 False
4 False
5 False

From my understanding both if statement should behave the same way.But the boolean is not. I can't understand why the boolean somehow becomes None. Can someone explain what is happening?

CodePudding user response:

This:

firstId = False if firstId else print(str(x)  " "   str(firstId))

is the same as

firstId = (False if firstId else print(str(x)  " "   str(firstId)))

i.e.

if firstId:
    firstId = False
else:
    firstId = print(str(x)  " "   str(firstId))

It always assigns a value to firstId, and the conditional expression on the right determines what that value is.

In the else case, the value is None, because print(...) returns None.

A conditional expression is not a one-line if statement. It is a different construction for a different purpose.

  • Related