Skip to content

Python conditional expression | Basics

  • by

Python has conditional expressions which are sometimes called a “ternary operator“. If you need to use statements, you have to use a normal if statement instead of a conditional expression.

In Python, the conditional expression is written as follows.

X if condition else Y

Python conditional expression example

Simple example code.

a = 10
result = 'Even' if a % 2 == 0 else 'Odd'

print(result)

Output:

Python conditional expression

List comprehensions and conditional expressions

l = [0 if i % 2 == 0 else 1 for i in range(10)]

print(l)

Output: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

Lambda expressions and conditional expressions

res = lambda x: 'even' if x % 2 == 0 else 'odd'

print(res(10))

Output: even

Does Python have a ternary conditional operator?

Answer: Yes, it was added in version 2.5. The expression syntax is:

a if condition else b

First condition is evaluated, then exactly one of either a or b is evaluated and returned based on the Boolean value of condition. If condition evaluates to True, then a is evaluated and returned but b is ignored, or else when b is evaluated and returned but a is ignored.

Source: stackoverflow.com

Use conditional expressions to assign a variable like so:

a = True
x = 0 if True else 1

print(x)

Output: 0

Do comment if you have any doubts or suggestions on this Python basic tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading