Rodrigo πŸπŸš€ Profile picture
Take your Python 🐍 skills to the next level πŸš€!

Sep 28, 2021, 30 tweets

Interested in improving your Python 🐍 skills?

πŸ€” If you are, have you learned about conditional expressions?

Here is a MEGA thread πŸ‘‡πŸ§΅ teaching you almost everything there is to know about conditional expressions!

I will include a bunch of examples πŸ–Ό, so don't worry!

This is the follow-up to my experiment from earlier today.

I tried teaching you about conditional expressions without words 😢.

Here is the original thread:

Alright, so conditional expressions aren't that hard, really.

It is just an expression: a piece of code that evaluates to a result.

But then, it is tied to a condition: depending on whether the condition is truthy or falsy, the final result changes.

Check the function below:

This function just checks if a number is odd or even.

It does so with an `if` statement and the condition `n % 2`, that just checks if `n` leaves a remainder when divided by 2.

Then, depending on whether the condition evaluates to truthy or falsy, we assign to parity.

But assigning to `parity` like that is what conditional expressions excel at!

Here's the same function, but using a conditional expression:

The conditional expression has three parts:

1. the value we want if the condition is truthy;
2. the condition to check; and
3. the value we want if the condition is falsy.

Here is the conditional expression from the function above.

Can you spot the three parts?

Here is a different example with a custom implementation of the built-in `abs` function.

Given a number, return the same number if the argument is already positive.

If it's negative, flip the sign:

Again, depending on whether the number is positive or not (the condition `x > 0`) we return one of two different values!

So...

Conditional expressions to the rescue!

Again, we can take a closer look at the conditional expression itself.

Can you figure out what are the three parts that make up this conditional expression?

Now, a conditional expression has three parts, and none of them are optional.

For example, it doesn't make sense to get rid of the `else ...` part:

So, if you have a variable that you may or may not want to modify, you need to do one of two things.

You can use a standard `if` statement to modify it in case you need that:

Ooooooor, you can use a conditional statement, but the expression that comes after the `else` is the variable itself.

This means the conditional expression acts as a β€œdo-nothing” if the condition is falsy:

Another cool thing about conditional expressions is that they do β€œshort-circuiting”.

I wrote about Boolean short-circuiting in depth in an article of mine (that you can see linked here) and short-circuiting for conditional expressions is similar.

mathspp.com/blog/pydonts/b…

Conditional expressions short-circuiting means that we only evaluate what we REALLY need.

So, we start by the condition (even though it comes second).

After the condition, we only evaluate the expression we need.

1/0 gives an error IF it gets evaluated, but it didn't:

At this point you may be starting to realise that conditional expressions and `if` statements are related.

But `if` statements also have `elif`s, so can we do that in conditional expressions as well?

You can, but you don't use the `elif` keyword.

Here's an example to consider:

To rework this into using conditional expressions, we first need to rejig this so it only uses `if`s and `else`s.

Why?

Because that's what conditional expressions know about.

So, first step, get rid of the `elif` with a nested `if` block:

After that, we can rewrite the bottom `if` block as a conditional expression:

After that, we get the `if` block pattern again, and that one we know how to replace with a conditional expression...

Even if one of the expressions itself IS a conditional expression!

We can just do it:

Now the question that arises is:

β€œCan I get rid of the parenthesis?”

Yes you can, removing the parenthesis doesn't change the value of the conditional expression:

This chaining of conditional expressions can become unwieldy fast, so try to not go crazy with it.

The next step in mastering conditional expressions is understanding the precedence that they have.

For example, in 3 + 4 * 5, the * happens first.

What about 3 + 4 if condition else 5?

What happens first?

Do we sum or do we evaluate the conditional expression?

As it turns out, the docs say that conditional expressions are the expressions that have the lowest precedence of all.

This means that we sum first and then evaluate the conditional expr.

This is shown here, as using parenthesis forces the conditional expression to go 1st:

Just for the sake of completeness, let me also show you this effect, but on the left of the addition, instead of on the right:

Because conditional expressions are just expressions, they can be used where other expressions make sense...

For example, in list comprehensions!

I remember I took a while to understand the difference between an `if` on the left and an `if` on the right of a list comp πŸ˜•πŸ€”πŸ˜΅

If it is on the right, it acts as a filter for the values we care about.

If you need to brush up your knowledge on list comprehensions, I got you πŸ˜‰

As for the `if` on the left, it's just a conditional expression.

So, `if`s inside list comps:
- on the left, modifies the final value in the list;
- on the right, filters values from the final list;

Here's a conditional expression in a list comprehension:

Can you do a similar thing with the conditional expression for the `abs` function?

Here, take these numbers: `[-42, 73, 0, -7]`.

Write a list comprehension that uses a conditional expression to compute the absolute value of each one of those numbers.

Done?

Here's my code:

πŸ†πŸ’ͺ Congratulations on making it this far!

That's it for this thread!

If you want to learn even more about conditional expressions, then check my Pydon't article on them!

I include even more examples, especially some from the Python Standard Library:

mathspp.com/blog/pydonts/c…

I write daily about Python 🐍, teaching you features, tricks, and more!

If you're learning Python 🐍...

Then you're going to love my content, so follow me β†’ @mathsppblog πŸ˜‰

Also, would you do me a HUGE favour and retweet the beginning of this thread?

To conclude, a TL;DR:

1. conditional expressions let you pick one of two values, depending on the value of a condition;

2. cond exprs have three composing parts;

3. all three parts HAVE to be there;

4. repeat a variable name if you want a conditional do-nothing assignment;

5. like in Boolean short-circuiting, cond exprs only evaluate what they need;

6. to emulate an `if` block with `elif`s, chain cond exprs from left to right;

7. cond exprs have the lowest precedence;

8. use them in list comps to conditionally modify values on the fly.

Bye πŸ‘‹

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling