5. Control Flow
Teaching your program to make decisions
A program that runs the same code every time isn't very useful. Real programs need to make decisions. Control flow is how you make that happen.
The if statement is the most fundamental decision-maker in all of programming:
Notice the indentation. In Python, indentation is not optional β it's how Python knows which code belongs inside the if block. Most other languages use curly braces {} instead.
Always use 4 spaces for each level of indentation. Never mix tabs and spaces. VS Code will handle this for you if you configure it correctly.
Nested Conditions
You can place if statements inside other if statements. This is called nesting, and it's useful when you need to check multiple layers of conditions:
Be careful with deep nesting β more than 2 or 3 levels becomes hard to read. Often, deeply nested code can be rewritten using logical operators (and, or) or by returning early from functions.
Switch Statements
Python 3.10 introduced match/case (equivalent to switch in other languages). It's cleaner than a long chain of elif when you're checking one variable against many specific values:
In JavaScript, the switch statement is more common:
Ternary Operators
A ternary operator is a compact way to write a simple if/else on one line. It's called ternary because it takes three parts:
Use ternary operators for simple yes/no assignments. If your logic is more complex, a regular if/else is clearer and more readable β don't sacrifice clarity for cleverness.
Real-World Logic Implementation
Let's put it all together with a real scenario β a basic login system:
Knowledge Check
Ready to test your understanding of 5. Control Flow?