What are if statements?
If statements let your program make decisions. They check if something is true or false, then act accordingly. Real-life logic:- IF it’s raining THEN take umbrella
- IF battery < 20% THEN charge phone
- IF password correct THEN allow access
Basic if statement
- Check the condition (
age >= 18) - If True, run the indented code
- If False, skip it
The colon
: and indentation are required! This is how Python knows what code belongs to the if statement.If-else statements
Handle both True and False cases:If-elif-else chains
For multiple conditions:Why
elif instead of multiple if statements? With elif, Python stops checking once it finds a true condition. This is more efficient and prevents multiple blocks from running. The order matters - always put more specific conditions first!Multiple conditions
Combine conditions withand, or, not:
Nested if statements
Put if statements inside other if statements:Common mistakes
Forgetting the colon
Forgetting the colon
Using = instead of ==
Using = instead of ==
Wrong indentation
Wrong indentation
Practice & Exercises
To reinforce what you’ve learned in this section (If, If-Else, and Elif Statements), practice with these interactive notebooks:Follow-Along Practice
Practice basic conditions, if-else branches, and nested logical expressions.💻 VS Code | 🚀 Colab | 📥 Download
Practice Exercises
Test your conditional logic skills with exercises on even/odd checkers and custom ticketing pricing rules.💻 VS Code | 🚀 Colab | 📥 Download
What’s next?
Now let’s learn about the clean pattern matching tool: Match Case!Match Case
Structural pattern matching for value checking