Module 3: Control Structures: Flow & Decision Making
Programs that only run from top to bottom are limited. Let's give your code a brain! This module teaches you how to make your programs evaluate conditions and make decisions.
1. Why Programs Need to Make Decisions
Think about your daily life. You constantly make decisions: If it's raining, you take an umbrella. If you're hungry, you eat. If the traffic light is red, you stop. Your actions change based on the conditions around you.
Powerful software does the same thing. A program needs to be able to respond differently to different situations. This is called **control flow**. Instead of just executing code line-by-line, we can direct the flow, creating branches and paths for our program to follow. The primary tool for this is the `if` statement.
🧠Core Concept: The Fork in the Road
Imagine your program is walking down a path. A conditional statement (`if`) is like a fork in that path. The program checks a sign (the condition) and decides whether to go left, go right, or continue straight ahead. This allows for dynamic and intelligent behavior.
2. The Basic Decision: The `if` Statement
The `if` statement is the simplest way to make a decision. It checks if a certain condition is true. If it is, a specific block of code is executed. If the condition is false, the program simply skips that block and moves on.
The syntax is crucial. It consists of the `if` keyword, followed by the condition, and then a colon (`:`). The code to be executed if the condition is true must be **indented** on the following lines.
Example: Checking the Weather
In this example, since `is_raining` is `True`, the program will print "Don't forget your umbrella!". The final print statement will always run because it is not indented under the `if`. If you change `is_raining` to `False`, only "Have a nice day!" will be printed.
Indentation is not optional in Python! It's how Python knows which code belongs to the `if` statement. A standard indentation is four spaces.
3. Crafting Conditions with Comparison Operators
Most conditions aren't just a single `True` or `False` variable. Usually, we need to compare values. We do this using **comparison operators**. These operators always result in a Boolean value (`True` or `False`).
Operator | Meaning | Example | Result |
---|---|---|---|
`==` | Equal to | `5 == 5` | `True` |
`!=` | Not equal to | `5 != 10` | `True` |
`>` | Greater than | `10 > 5` | `True` |
`<` | Less than | `10 < 5` | `False` |
`>=` | Greater than or equal to | `5 >= 5` | `True` |
`<=` | Less than or equal to | `10 <= 5` | `False` |
Example: Age Restriction
4. Handling Alternatives with `else` and `elif`
What if you want to do something specific when the `if` condition is false? That's where the `else` statement comes in. It provides an alternative block of code to run.
`else`: The "Otherwise" Block
The `else` block will only execute if the `if` condition (`age >= 18`) is `False`.
`elif`: Checking Multiple Conditions
Sometimes you have more than two possibilities. You can use `elif` (short for "else if") to check for additional conditions in a sequence. Python will check them one by one and run the code for the first one that is true.
Example: Grading System
Here, because `score` (85) is not `>= 90`, the first condition is false. It moves to the next `elif`. Since `85` is `>= 80`, it prints "Grade: B" and the entire `if/elif/else` chain stops. The `else` block at the end acts as a catch-all if none of the preceding conditions are met.
5. Truthiness: More Than Just `True` or `False`
In Python, conditions don't have to be strictly `True` or `False`. Python has a concept of **"Truthiness"**, where other values can be treated as true or false in a conditional context.
💡 Core Concept: Truthy vs. Falsy
Falsy Values: These are values that Python considers to be `False` in an `if` statement.
- The number `0` (and `0.0`)
- An empty string `""` or `''`
- An empty data structure (like an empty list `[]`, which we'll see later)
- The special value `None`
Truthy Values: Essentially, everything else! Any non-zero number, any non-empty string, etc., is considered `True`.
Example: Checking for User Input
Instead of writing `if user_name != ""`, we can use truthiness to write cleaner code:
This is a common and elegant way to check if a variable has a meaningful value.
6. Nested Conditionals
You can place `if/elif/else` structures inside other `if/elif/else` structures. This is called **nesting** and allows for more complex, layered logic.
Example: Ticketing System
Imagine a ticketing system that checks age and if the person has a student ID.
Be careful with nesting. If it gets too deep (more than 2 or 3 levels), your code can become very hard to read and manage.
You've Completed Module 3!
Fantastic! You can now control the flow of your programs, allowing them to make smart decisions and respond to different inputs. This is a massive step towards writing truly useful applications.
Next, we'll learn how to make programs repeat actions without rewriting code, using the power of loops.
On to Module 4: Loops and Iteration →