r/AskAnythingPython • • Sep 08 '23

if else in one line!

just wanted to share something cool I found, - you can write the if-else statement in one line!

so instead of

age =20

if age>=18:

print("You can drive")

else:

print("Sorry, you cant drive")

you can write them in one line - this is called a terinary conditional operator. Means you need three operands (The 2 print statements and the test condition)

print("You can drive") if age>=18 else print("Sorry, you cant drive")

The syntax is as follows

a if condition else b
1 Upvotes

14 comments sorted by

View all comments

Show parent comment

1

u/jemdoc Sep 09 '23

A variation is

message=["Sorry, you can't drive","You can drive"][age>=18]

which is useful for code golf and not much else.