# 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

value_if_true if condition else value_if_false

## Example 1: Basic Conditional Assignment

### Visual Representation

Assign a value to a variable based on a condition.

age = 20

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

print(status)

Output

## Example 2: Within List Comprehensions

### Visual Representation

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)

Output

Welcome, User!

## Example 4: Nested Inline If

return "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "D"

# Test the function with different scores