dhairyashah
Portfolio

May 19th, 2023

How to use ternary operators in Python?

Author Picture

Dhairya Shah

Software Engineer

Ternary operators are the shorthand method to call the conditional statement.

General Syntax

<result_if_true> if <condition> else <result_if_false>

Explanation

Let’s say you want to create a function that compares the age variable to 18 and returns True or False depending on the value of the age variable.

The first thing, that comes to your mind is to run if...else statement,

def check_age(age):
    if age >= 18:
        return True
    else:
        return False

Instead of writing all this code just to compare age or any other condition. You can use the ternary operator.

Here’s, how ternary operators are used:

def check_age(age):
    return True if age >= 18 else False

The same condition is satisfied leaving fewer lines of code used and keeping the code clean.

I hope you learned something new, thanks for reading!