Chapter 20 of 20

Python Conditional Expressions

Sometimes we need to choose between two values based on a condition. Writing a complete if-else block for a simple decision can feel a little unnecessary.

Python gives us a shorter way to do this called a conditional expression.

What is a Conditional Expression?

A conditional expression is a one-line way to choose between two values based on a condition.

The basic syntax is:

value_if_true if condition else value_if_false

For example:

age = 20

status = "Adult" if age >= 18 else "Minor"

print(status)

Output:

Adult

Python checks age >= 18. If it's true, "Adult" is assigned to status; otherwise, "Minor" is assigned.

Traditional if-else vs Conditional Expression

Without a conditional expression:

age = 20

if age >= 18:
    status = "Adult"
else:
    status = "Minor"

Using a conditional expression:

age = 20

status = "Adult" if age >= 18 else "Minor"

The second version is shorter and works nicely when the decision is simple.

Another Example

Let's check whether a number is even or odd:

number = 7

result = "Even" if number % 2 == 0 else "Odd"

print(result)

Output:

Odd

Here, the expression:

"Even" if number % 2 == 0 else "Odd"

means:

If the number is divisible by 2, use "Even"; otherwise, use "Odd".

Using Conditional Expressions in print()

You don't always need to store the result in a variable.

age = 16

print("Adult" if age >= 18 else "Minor")

Output:

Minor

This is useful for very small decisions.

Nested Conditional Expressions

Python also allows conditional expressions inside other conditional expressions:

marks = 85

grade = "A" if marks >= 90 else "B" if marks >= 75 else "C"

print(grade)

Output:

B

However, nested conditional expressions can become difficult to read. If the logic gets complicated, a normal if-elif-else statement is usually a better choice.

When Should You Use Them?

Conditional expressions are best when the decision is short and easy to understand.

Good example:

age = 20
status = "Adult" if age >= 18 else "Minor"

For more complicated logic, use a normal conditional statement:

if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 40:
    grade = "C"
else:
    grade = "F"

This is much easier to read than trying to squeeze everything into one line.

Practical Example

Let's create a simple shipping message:

amount = 1200

message = "Free shipping" if amount >= 1000 else "Shipping charges apply"

print(message)

Output:

Free shipping

So, conditional expressions are basically compact if-else statements. They're great for simple decisions, but don't force complicated logic into one line just to make the code shorter.