Rodrigo πŸπŸš€ Profile picture
Sep 28, 2021 β€’ 30 tweets β€’ 10 min read β€’ Read on X
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 πŸ‘‹

β€’ β€’ β€’

Missing some Tweet in this thread? You can try to force a refresh
γ€€

Keep Current with Rodrigo πŸπŸš€

Rodrigo πŸπŸš€ Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @mathsppblog

May 9
Hide private information in your Python code.

Suppose you want to print an email...

But you want to create that cool ro*****@mathspp.com effect.

This is pretty easy to achieve in Python!

All you need to do is use an f-string and use the appropriate format specifiers. Diagram showing how you can use f-strings and their format specification to redact private or sensitive information, like email addresses.  The code from the diagram:  def redact_email(email):     user, _, domain = email.partition("@")     return f"{user[:2]:*<{len(user)}}@{domain}"  print(redact_email("rodrigo@mathspp.com")) # ro*****@mathspp.com
πŸ‘‰ the first thing you do is use `str.partition` to grab the email β€œuser” and the domain.

We will redact only the user (but you could also redact the domain with the same process).

The `user[:2]` shows the first two characters.

That's the β€œro”.

But how do you get β€œro*****”?
πŸ‘‰ use an f-string and the width specifier.

You want to create a field as wide as β€œrodrigo”:

r o _ _ _ _ _

The length of this field is `len(user)`, so you use `{len(user)}` INSIDE the format spec.

This creates a field with the correct width.
Read 6 tweets
May 18, 2023
I know `print` is the first Python 🐍 function you learned! πŸš€

And yet, you don't know this about `print` πŸ‘‡ Image
What you know for sure is that `print` will take an object and it will print it on the screen.

That's the basic functionality it provides: Image
Maybe you don't know that `print` can actually print multiple things!

If you pass multiple arguments, they all get printed: Image
Read 11 tweets
May 17, 2023
I'll tell you the story of a person that had the wrong name…

And how to prevent that in Python 🐍 with properties πŸš€.

πŸ‘‡ Image
John Doe was a regular guy and when he was born, he was inserted into the government's database of people.

They created a new `Person` and added John's details: Image
John never liked his name Doe, though.

So Joe decided to change his name to Smith.

And so he did.

He updated his last name, but the government `Person` STILL had the wrong name! Image
Read 10 tweets
May 14, 2023
Opening a file to read/write is a common task in Python 🐍.

Here is how to do it right! πŸš€

πŸ‘‡ Image
Python has a built-in `open` that takes a file path and opens that file.

Then, you have to specify whether you want to open the file to read, write, or append.

But this isn't half of the story! Image
The default behaviour is to open the file to read/write text.

This works well with TXT or CSV files, for instance.

If you need to open a file to read its binary contents, you can add a `"b"` to the mode: Image
Read 6 tweets
May 13, 2023
The Python 🐍 built-in `round` is great. πŸš€

Here are some tips on it. πŸ‘‡ Image
The purpose of `round` is to… round numbers!

It rounds numbers to the closest integer.

These are some simple examples: Image
However, if the number ends in `.5`, what is the closest integer?

In that case, `round` will choose the even number.

This means it may round up or down πŸ€ͺ

(In school, I was taught to round `.5` up… 🀷) Image
Read 6 tweets
May 12, 2023
Error handling in Python 🐍 made simple. πŸš€

πŸ‘‡ Image
The keyword `try` is used before code that might fail.

So, if you know something can raise an error, you can write it inside a `try` statement: Image
Now that the code is inside a `try` statement, you need to tell Python what error you want to handle, and how.

That's when the keyword `except` comes in! Image
Read 7 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us!

:(