Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Conditional Expressions

In this video, you’ll meet the Conditional Expression, which is some sort of one-line if-else-statement. The basic syntax is as follows:

Python
<statement1> if <expr> else <statement2>

00:00 Section 4: Conditional Expressions. Conditional expressions are slightly confusing at first. They kind of look like a one-liner, but they’re written differently.

00:12 If it helps, you can think of them as a one-line if/else statement. Think back to the if/else syntax.

00:21 A conditional expression is just taking this syntax and streamlining it so it looks like this. You can see now the expression sits in the middle, <statement1> comes first if <expr> is True, or else we use <statement2>. You’ll see this most often used as a way to assign variables based on the results of a comparison.

00:48 Let’s hop into the console and I’ll show you what that looks like. We need a variable or something to compare in our conditional expression, so let’s give it dog_lover is True. And let’s set up another variable.

01:10 Let’s say you want to use a conditional expression to assign this variable, buy_a_dog. We need our first statement, which will just simply be "Yes" if dog_loverif dog_lover evaluates to Trueelse "Nope", we’re not going to buy a dog.

01:36 So, see if you can work this out in your head real quick and then press Enter. Oh, I’m missing the r on dog_lover. Let’s try that again.

01:47 And now I’ll hit Up arrow twice to get back to my conditional. Now let’s see what the buy_a_dog variable contains.

01:57 We get 'Yes'. If I switch dog_lover to False and run the conditional expression again, buy_a_dog will be 'Nope'.

02:10 That’s it for conditional expressions, my friend. See you in the next one!

Zarata on April 7, 2020

Oops. Your one slide states:

<statement**1**> if <expr> else <statement**1**>

You’re fine in the example block above this comment :)

smohankumar7 on May 21, 2022

yes, please correct it

Martin Breuss RP Team on May 22, 2022

The lesson is updated now, thanks for the heads-up Zarata and smohankumar7 :)

Become a Member to join the conversation.