Python Ternary Operator Tutorial

Drag to rearrange sections
Rich Text Content

In this tutorial, we will learn what the ternary operator is and how to use it in Python.

What is Ternary Operator? (Python if else one line)

The ternary operator is a shorter version of an if-else statement.

Basically, we use the ternary operator when we want to run a short (single line) conditional statement and return a value based on the result of the condition.

Python Ternary Operator Declaration

This is how we can declare a ternary operator in Python:

[value_on_true] if [expression] else [value_on_false]

`value_on_true`: this is the value that will be returned if the result of the expression in the ternary operator is True.

`if`: after the `value_on_true` we put the keyword `if` in order to define the expression of the ternary operator.

`expression`: this is where put the expression to be evaluated.

`else`: after the expression, comes the `else` keyword, which is used to declare the value that should be returned if the result of the `expression` was False.

`value_on_false`: This value will be returned if the result of the `expression` is False.

Example: python conditional assignment

val = 500

res = 200 if val<600 else 1000

print(res)

Output:

200

Here, the condition is to see if the value of the `val` variable is less than the value 600. If it was, then the value 200 will be assigned to the `res` variable. Otherwise, the value 1000 returns and will be assigned to the `res` variable.

So here because the result of the condition is True, then the value `200` returned as a result.

More to Read

If you liked this tutorial and want to learn more, you can check the EnjoyTutorials.com where we explained at ease, the core of programming languages like Python, JavaScript, and many more...

rich_text    
Drag to rearrange sections
Rich Text Content
rich_text    

Page Comments