How to Use inline if in Python

In Python, an inline if is a way to write an if-else statement in a single line.

It’s a more concise way to evaluate conditions and is often used for simple assignments or when you need to make a decision within an expression.

Syntax

Syntax of Inline if statement in Python

value_if_true if condition else value_if_false

Example 1: Basic Conditional Assignment

Visual Representation

Basic Conditional Assignment

Assign a value to a variable based on a condition.

age = 20

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

print(status) 

Output

Adult

Example 2: Within List Comprehensions

Visual Representation

Within List Comprehensions

Apply conditional logic inside a list comprehension.

numbers = [1, 2, 3, 4, 5]

squared_even_numbers = [x**2 if x % 2 == 0 else x for x in numbers]

print(squared_even_numbers) 

Output

[1, 4, 3, 16, 5]

If x % 2 == 0 (which means if x is even), then it calculates x**2 (x squared).

If x is not even (i.e., x is odd), then it just takes x as it is.

Example 3: In Function Arguments

def greet(message):
 print(message)

user_is_admin = False

greet("Welcome, Admin!" if user_is_admin else "Welcome, User!")

Output

Welcome, User!

Example 4: Nested Inline If

def determine_grade(score):
 return "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "D"

# Test the function with different scores
print(determine_grade(95)) 
print(determine_grade(85)) 
print(determine_grade(75)) 
print(determine_grade(65)) 

Output

A
B
C
D

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.