HomepythonIf-elif-else instruction in Python, including truth checks and ternary (three-place) if/else expressions.

If-elif-else instruction in Python, including truth checks and ternary (three-place) if/else expressions.

if-elif-else Instruction

The if-elif-else statement is used for conditional execution of code blocks based on the evaluation of boolean expressions. Here’s how each part works:

  • if Statement: Evaluates a boolean expression. If the expression is True, it executes the corresponding block of code.
  • elif Statement: Short for “else if”. If the preceding if or elif condition was False, it evaluates the current boolean expression. If True, it executes the corresponding block of code.
  • else Statement: If all preceding conditions were False, it executes the corresponding block of code.

Syntax

if condition1:
    # Code block executed when condition1 is True
elif condition2:
    # Code block executed when condition2 is True
else:
    # Code block executed when all preceding conditions are False
Python

Example

age = 25

if age < 18:
    print("You are a minor.")
elif age < 65:
    print("You are an adult.")
else:
    print("You are a senior citizen.")
Python

Output:

You are an adult.
Python

Truth Check

In Python, any object can be tested for a truth value. The following values are considered False in a boolean context:

  • None
  • False
  • Zero of any numeric type: 0, 0.0, 0j, etc.
  • Any empty sequence: '', (), []
  • Any empty mapping: {}

All other values are considered True.

Example

value = ""

if value:
    print("The value is true.")
else:
    print("The value is false.")
Python

Output:

The value is false.
Python

Ternary (Three-Place) If/Else Expression

Python supports a concise way to write if-else statements using a ternary conditional operator. It’s a single-line expression that returns one of two values based on the evaluation of a condition.

Syntax

value_if_true if condition else value_if_false
Python

Example

age = 20

status = "minor" if age < 18 else "adult"
print(status)  # Output: adult
Python

Detailed Examples

Complex if-elif-else

Let’s consider a more complex example involving multiple conditions:

temperature = 30

if temperature < 0:
    print("Freezing weather")
elif 0 <= temperature < 10:
    print("Very Cold weather")
elif 10 <= temperature < 20:
    print("Cold weather")
elif 20 <= temperature < 30:
    print("Normal in Temp")
elif 30 <= temperature < 40:
    print("It's Hot")
else:
    print("It's Very Hot")
Python

Output:

Normal in Temp
Python

Truthy and Falsy Values

Here’s how different values are evaluated in conditions:

values = [None, False, 0, 0.0, '', [], {}, "hello", [1, 2, 3], {1: "one"}]

for value in values:
    if value:
        print(f"{value} is True")
    else:
        print(f"{value} is False")
Python

Output:

None is False
False is False
0 is False
0.0 is False
 is False
[] is False
{} is False
hello is True
[1, 2, 3] is True
{1: 'one'} is True
Python

Using Ternary Operator

Here’s an example using the ternary operator for a quick decision-making process:

num = 5

result = "Even" if num % 2 == 0 else "Odd"
print(result)  # Output: Odd
Python

Combining if-elif-else with Functions

You can also use conditional statements within functions to determine outputs based on inputs:

def evaluate_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

print(evaluate_grade(85))  # Output: B
Python

These examples cover the basic and some advanced uses of conditional statements in Python. Understanding these concepts is crucial for writing effective and efficient Python code.

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular