Skip to main content

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

How it works:
  1. Check the condition (age >= 18)
  2. If True, run the indented code
  3. 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:
Python checks each condition in order and runs the first True one.
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 with and, or, not:

Nested if statements

Put if statements inside other if statements:

Common mistakes

What’s next?

Now let’s learn about loops to repeat code efficiently!

Loops

Repeat code without copying