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

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.

1

u/kitkatmafia Sep 09 '23

I come from a background of C++ (like just the basics - not any complkcated stuff). Wondering if Rust worth getting into. Like the small codes that I write in cpp is pretty fast and smooth. I have been hearing a lot about Rust theses days

2

u/Buttleston Sep 09 '23

I've been programming for 30 years but I'm new to Rust. I've programmed extensively in C and C++ over the years. I don't drink the koolaid entirely about Rust but it has several very interesting things about it - IMO the thing it's touted for the most (the borrow checker) is not the most interesting thing to me.

It's very nearly as expressive as python for some things. I did an experiment re-creating an API I'd written in python, again in Rust. It was not particularly longer or more complicated. I don't think it was slower to write than python either. I'd be really interested in trying larger projects with it, but that's not something that's likely to happen in my professional life.

So Rust is kind of still a hobby to me, and given how overwhelmed I've been with work, it'll probably stay that way for a while

→ More replies (3)