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/kitkatmafia Sep 09 '23

Scala is meesing things up, it has a whole different idea of programming, i tried giving it a shot and gave up. id prefer sometihng python style