Control Flow — Conditionals & Loops
So far, your programs execute every line from top to bottom. But real programs need to make decisions and repeat actions. That's what control flow gives you.
Conditionals: If / Else
Conditionals let your program choose different paths based on conditions:
- if: "If this condition is true, do this"
- else if / elif: "Otherwise, if this other condition is true, do that"
- else: "If nothing above was true, do this as a fallback"
The condition is always an expression that evaluates to true or false.
Comparison Operators
| Operator | Meaning |
|----------|---------|
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
Loops: For and While
Loops repeat a block of code:
- For loop: When you know how many times to repeat
- While loop: When you repeat until a condition becomes false
Avoiding Infinite Loops
A while loop runs forever if its condition never becomes false. Always make sure something inside the loop changes the condition — otherwise your program will freeze.
Try It Yourself
- Change the temperature value and run again — see which branch executes
- Write a loop that prints the first 10 even numbers
- Create a "guess the number" game using a while loop