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
What’s next?
Now let’s learn about loops to repeat code efficiently!Loops
Repeat code without copying