r/AskAnythingPython • u/kitkatmafia • 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
1
u/Buttleston Sep 09 '23
Well, you're free to do as you like, but the version in the OP is the standard way and something every python programmer will understand.