Writing if statements as one-liners

  • A+
Category:Languages

I want to write one-liner if statements when i can avoiding two lines of code.

if 10>5:     print( "10 is greater than 5" ) else:     print( "nothing here " ) 

While the following statement is correct:

print( "10 is greater than 5" ) if 10>5 else print( "nothing here " ) 

This does give me the error SyntaxError: unexpected EOF while parsing if i remove the else cause:

print( "10 is greater than 5" ) if 10>5 

 


print is a function, and it takes a single value. In other words, you need a single call to print, and represent the value it takes as a onliner if:

print ("10 is greater than 5" if 10 > 5 else "nothing here") 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: