Programs need to make decisions. Should we show an error message? Grant access? Display a discount? This is where conditional statements come in - they let your code choose different paths based on conditions.
The simplest conditional - do something IF a condition is true:
Python uses indentation (typically 4 spaces) to define code blocks. Everything indented after the if statement runs only when the condition is true. The non-indented line runs regardless.
What if the condition is false? Use else to handle that case:
For multiple conditions, use elif (short for "else if"):
Python checks conditions top to bottom and stops at the first match. If we checked score >= 60 first, a score of 95 would get a "D"! Always order from most specific to least specific.
Create a simple access control system. Check if a user has the right credentials!
Given user_role = "admin", print:
- "Full access granted" if role is "admin"
- "Limited access granted" if role is "user"
- "Access denied" for anything else
You can make decisions in code! Let's learn about comparison operators.
Conditions use comparison operators to compare values. These operators always return True or False.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
> |
Greater than | 10 > 5 |
True |
< |
Less than | 3 < 7 |
True |
>= |
Greater than or equal | 5 >= 5 |
True |
<= |
Less than or equal | 4 <= 4 |
True |
= is assignment (puts a value in a variable)
== is comparison (checks if two values are equal)
This is one of the most common beginner mistakes!
Strings are compared alphabetically (lexicographically):
Python allows elegant chained comparisons:
Use comparison operators to classify a number.
Given num = 0, print:
- "Positive" if num > 0
- "Negative" if num < 0
- "Zero" if num == 0
You can compare values. Now let's combine conditions with logical operators!
What if you need to check multiple conditions? Logical operators combine boolean expressions!
| Operator | Meaning | Example | Result |
|---|---|---|---|
and |
Both must be True | True and False |
False |
or |
At least one must be True | True or False |
True |
not |
Inverts the boolean | not True |
False |
In Python, values can be evaluated as boolean even if they're not True/False:
Python is smart! With and, if the first condition is False, it doesn't check the second (result is already False). With or, if the first is True, it doesn't check the second. This can prevent errors!
Create a login validator using logical operators!
Given username = "admin" and password = "secret123":
- Print "Login successful!" if BOTH are correct
- Print "Invalid credentials!" otherwise
(Correct: username="admin", password="secret123")
You can combine conditions. Now let's learn about loops!
Loops let you execute code multiple times. Python has two main loop types: while and for.
Repeats while a condition is True - useful when you don't know how many times to repeat:
If the condition never becomes False, the loop runs forever! Always make sure your loop has a way to end (like incrementing a counter).
Iterates over a sequence (list, string, range) - perfect when you know what to iterate:
Generates a sequence of numbers - perfect for loops!
for: Use when you know the items/count (iterate through a list, run 10 times)
while: Use when you don't know when to stop (keep asking until valid input)
Use a for loop to generate a multiplication table!
Given num = 5, print the multiplication table from 1 to 5:
5 x 1 = 5
5 x 2 = 10
... and so on
You can repeat actions! Let's learn to control loop flow.
Sometimes you need more control over loops - exit early, skip iterations, or do something when the loop completes normally.
Immediately exits the loop, even if the condition is still True:
Skips the rest of the current iteration and goes to the next:
The else block runs only if the loop completes without hitting break:
You can put loops inside loops! break only exits the innermost loop. For complex nested loop control, consider using functions with return.
Use a loop with break to check if a number is prime!
Given num = 17, check if it's prime (divisible only by 1 and itself).
Print "Prime!" or "Not prime!"
You have full control over loops! Time for the summary.
Congratulations! You've completed Chapter 3 and mastered Python flow control. Let's recap:
Order matters! Check most specific conditions first.
== compares, = assigns. Never confuse them!
for when you know iterations, while when you don't.
break exits, continue skips, else runs if no break.
You've mastered Python flow control. Ready to prove your skills?