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

29 Sep
I challenged you πŸ†...

You delivered πŸ’ͺ!

I asked you to implement the sign function in Python 🐍.

Now I'll go over some alternatives and tell you what I like βœ… and dislike ❌ about them.

I'll also tell you which one I think is the best, most Pythonic ✨ one.

πŸ‘‡πŸ§΅ Image
By the way, for reference, here is the original challenge:

Let's start with the β€œbasic” `if: ... elif: ... else: ...` approach first.

Gets the job done, is simple, and is easy to ready.

Funnily enough, the only one to share that solution was a _very_ seasoned Python 🐍 programmer, author and trainer, @dabeaz πŸ™ƒ

Now, a couple of notes: Image
Read 28 tweets
28 Sep
πŸ€” If you are learning Python 🐍, I want to do an experiment:

Here's a thread πŸ‘‡πŸ§΅ teaching you conditional expressions.

BUT, I will teach you with NO words 😢

I will only show code snippets and examples.

Check the thread out carefully πŸ” and then give me your feedback!
By the way, if you want to learn something from this thread...

I'm not going to lie, you'll have to focus πŸ”.

Also, what's the rationale for this crazy πŸ€ͺ thread?

By reading code and examples, you see first-hand how the feature is used and where it comes in handy.

Let's go:
Read 17 tweets
26 Sep
Have you heard that Python 🐍 3.10 will be released soon?

Are you ready for when it drops πŸ’£πŸ”₯?

Python 3.10 will ship with the new ✨ match statement, and I created a cheatsheet just for that.

This is also a thread πŸ‘‡πŸ§΅ that breaks it down and explains everything:
The cheatsheet is free and teaches you 12+ things about the new `match` statement.

From the basics, to object destructuring, to wildcards, among other things.

Get it from the link πŸ‘‡, and keep reading below to learn all about the `match` statement.

mathspp.gumroad.com/l/cheatsheet_m…
In its most basic form, a `match` statement kind of resembles an `if` statement.

That's what most of the β€œswitch” or β€œmatch” statements in other languages do: a series of `if` / `elif` / `else` statements.

Even a basic `case` is powerful: use `|` to separate multiple options. Image
Read 23 tweets
25 Sep
What's the BEST way to learn Python 🐍?

I've been writing Python for 10 years and taught 100s of people.

Here is a FAQ with actionable advice πŸ‘‡πŸ§΅

But everyone is different, so share your thoughts as well πŸ‘‡πŸ’¬ to help as many as possible!
🐍 β€œHow do I start learning Python?”

Well, I think the answer to this question greatly depends on whether you have (considerable) programming experience with another language or not.

That's because β€œlearning Python” can mean ”learn the syntax of the language”, but...
... it can also mean ”learn how to think like a programmer”.

And, in my opinion, this is something very fundamental that you have to understand!

Being a programmer is also about having that programmer mindset.

Worry not, you can learn it 😊
Read 35 tweets
24 Sep
Do you want to master Python 🐍 list comprehensions?

Do you want to become more proficient working with lists in Python 🐍?

If you answered with β€œyes”, then here's a cheatsheet of mine to help you out.

This is also a thread πŸ‘‡πŸ§΅ that breaks it down and explains everything:
First off, here is the anatomy of a list comprehension.

There's 4 parts to a list comp:
1. enclosing brackets to create the list [];
2. expression that transforms your data;
3. `for` iteration over the initial data;
4. (optional!) condition to filter some data.
Do list comprehensions look confusing?

Maybe.

But that's because you didn't realise that list comprehensions have equivalent `for` loops!

The coloured boxes below show the equivalent bits in the list comp and in the `for` loop:
Read 19 tweets
23 Sep
Do you know what the Python 🐍 `type` is?

But do you _really_ know what it is?

Here is a valuable thread that will give you insights into what `type` is and does.

Let's go πŸ‘‡πŸ§΅
What does `type` do?

You might say that `type` takes an object and returns the type of the argument.

Here are some examples:
Fine, so `type` is a function!

Or is it..?

Take a look at the example above.

`sum` is a built-in function and `type(sum)` returned β€œbuilt-in function or method”.

So, logically, if `type` is a (built-in) function, the type of `type` should give the same thing:
Read 14 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

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

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(