Python Conditional Statements Tutorial

Introduction

Conditional statements in Python allow you to execute certain pieces of code based on the value of some conditions. The most common conditional statements are if, else, and elif.

if Statement

The if statement is used to test a condition. If the condition is true, the block of code inside the if statement will be executed.

age = 18
if age >= 18:
    print("You are an adult.")
        
You are an adult.
        
Question: What happens if age is less than 18?
Answer: If age is less than 18, the condition age >= 18 will be false, and the block of code inside the if statement will not be executed.

else Statement

The else statement can be combined with an if statement to provide an alternative block of code to execute if the condition is false.

age = 16
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")
        
You are a minor.
        
Question: Can an else statement exist without an if statement?
Answer: No, an else statement cannot exist without an if statement. It is always paired with an if statement to handle the false case.

elif Statement

The elif statement stands for "else if" and allows you to check multiple conditions sequentially. Once a condition is true, the corresponding block of code is executed, and the rest of the elif statements are skipped.

age = 20
if age < 13:
    print("You are a child.")
elif age < 18:
    print("You are a teenager.")
else:
    print("You are an adult.")
        
You are an adult.
        
Question: What will be the output if age is 15?
Answer: If age is 15, the output will be "You are a teenager." because the condition age < 18 will be true.

Combining if, elif, and else

You can combine if, elif, and else statements to create complex conditional logic.

score = 75
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")
        
Grade: C
        
Question: What will be the output if score is 85?
Answer: If score is 85, the output will be "Grade: B" because the condition score >= 80 will be true.

Conclusion

Conditional statements are a fundamental part of programming that allow you to control the flow of your program based on different conditions. By understanding and using if, else, and elif statements, you can create more complex and flexible programs.