fbpx

Conditional Statements in Python: if, elif, and else

Conditional statements are fundamental to programming, allowing you to make decisions in your code based on certain conditions. In Python, you can use the if, elif (else if), and else statements to control the flow of your program.

1. The if Statement:

The if statement is used for basic decision-making. It executes a block of code only if a specified condition is true.

# Example of the if statement
age = 20

if age >= 18:
    print("You are an adult.")

2. The if-else Statement:

The if-else statement allows you to execute different blocks of code based on the condition. If the condition in the if statement is true, the corresponding block is executed; otherwise, the block in the else statement is executed.

# Example of the if-else statement
age = 15

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

3. The if-elif-else Statement:

The if-elif-else statement is used when you have multiple conditions to check. The elif (else if) block allows you to add additional conditions.

# Example of the if-elif-else statement
score = 85

if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
else:
    grade = 'C'

print("Your grade is:", grade)

4. Nested Conditional Statements:

You can nest conditional statements inside each other to handle more complex scenarios.

# Example of nested if-else statements
age = 25
income = 50000

if age >= 18:
    if income > 30000:
        print("You qualify for the loan.")
    else:
        print("Your income is too low.")
else:
    print("You are not eligible for the loan.")

5. Ternary Operator:

Python also supports a ternary operator, which is a concise way to express conditional statements in a single line.

# Ternary operator example
age = 22
status = "Adult" if age >= 18 else "Minor"
print("Status:", status)

6. Conclusion:

Conditional statements are crucial for creating dynamic and responsive programs. They allow your code to adapt and make decisions based on varying conditions. Whether you need to check a single condition or handle multiple scenarios, Python’s if, elif, and else statements provide the flexibility to control the flow of your program effectively.

In the next sections, we’ll explore more advanced topics and practical applications of control flow in Python.