Skip to content
Home » The Ternary if Statement in Python

The Ternary if Statement in Python

Spread the love

In one of the previous articles we were talking about conditional statements. Today we’ll be talking about the ternary if statement.

Here’s the video version of this article:

We can simplify short conditional statements and the blocks that follow by using the so-called ternary if statement. Here’s a simple regular piece of conditional code:

 >>> a, b = 7, 3
 >>> if(a > b):
 ...     winner = a
 ... else:
 ...     winner = b
 ...  

We can now rewrite the code using the ternary if statement:

 winner = a if (a > b) else b 

The general syntax is:

 x = a if(condition) else b 

So, a is assigned to x provided the condition is met. Otherwise, b is assigned to x.

Ternary if Statement in Expressions

The ternary if statement can be also used in expressions, like for example:

 >>> a, b = 5, 8
 >>> result = 4 * (a if (a != b) else b ** 2) / 2
 >>> result
 10.0 

The condition to check here is whether a is not equal to b. As a equals 5 and b equals 8, they’re definitely not equal, so the condition is met. This entails using the value of a, which is 5, in the calculations:

 4 * 5 / 2 = 10.0

Now, let’s make the two variables equal:

 >>> a = b = 5
 >>> result = 4 * (a if (a != b) else b ** 2) / 2
 >>> result
 50.0 

Now the condition is not met, so b ** 2 is chosen for the calculations:

 4 * 5 ** 2 / 2 = 4 * 25 / 2 = 50.0 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love
Tags:

Leave a Reply