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
4
u/dnswblzo Sep 08 '23
It's worth noting that this also works to evaluate an expression to one value or another, which you can then assign or pass to something. For example, if you wanted one of those two messages, but wanted to do something other than printing, you can get one message or the other this way:
Or use it with a single call to
print():1
u/Buttleston Sep 09 '23
This is roughly equivlant to the trinary operation you find in a lot of languages, that is usually something like
foo = condition ? trueresult : falseresult
if condition is true, foo will equal trueresult, else false result. I find this more readable than python's version, but that's probably because I encountered it decades earlier.
Something I really like about Rust is that every code block returns a value. This means... for loops can return values. If blocks can return values. Etc. It's actually really handy and elegant.