Learning Objectives: After this lesson, you'll learn to control program flow with if statements, master comparison and logical operators, and understand how Python evaluates boolean expressions.
Introduction to Conditional Logic
Programs need to make decisions based on different situations. Python uses conditional statements to execute different code paths depending on whether conditions are true or false.
Think of it like a flowchart in your daily life:
- If it's raining → take an umbrella
- If you're hungry → eat something
- If it's late → go to sleep
Basic If Statements
The simplest conditional statement is the if
statement:
Loading Python runtime...
Key Points:
- The condition must evaluate to
True
orFalse
- Code inside the
if
block is indented (usually 4 spaces) - If the condition is
False
, the indented code is skipped
If-Else Statements
Use else
to specify what happens when the condition is False
:
Loading Python runtime...
If-Elif-Else Chains
For multiple conditions, use elif
(else if):
Loading Python runtime...
Comparison Operators
Python provides several operators to compare values:
Operator | Meaning | Example | Result |
---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
< | Less than | 3 < 5 | True |
> | Greater than | 5 > 3 | True |
<= | Less than or equal | 3 <= 3 | True |
>= | Greater than or equal | 5 >= 5 | True |
Loading Python runtime...
Logical Operators
Combine multiple conditions using logical operators:
Operator | Meaning | Example | When True |
---|---|---|---|
and | Both conditions true | a and b | Both a AND b are true |
or | At least one true | a or b | Either a OR b (or both) is true |
not | Opposite | not a | a is false |
Loading Python runtime...
Truthiness in Python
Python considers some values as "falsy" and others as "truthy":
Loading Python runtime...
Nested Conditions
You can put if statements inside other if statements:
Loading Python runtime...
Practical Examples
Example 1: User Authentication System
Loading Python runtime...
Example 2: Shipping Calculator
Loading Python runtime...
Practice Exercises
Exercise 1: Age Category Classifier
Loading Python runtime...
Exercise 2: Grade Calculator with Validation
Loading Python runtime...
Key Takeaways
✅ If statements control program flow based on conditions
✅ Indentation matters - Python uses indentation to group code blocks
✅ Comparison operators (==
, !=
, <
, >
, <=
, >=
) compare values
✅ Logical operators (and
, or
, not
) combine conditions
✅ Truthiness - Empty containers and zero values are "falsy"
✅ elif chains handle multiple exclusive conditions
✅ Nested conditions allow complex decision trees
Next Steps
In the next lesson, we'll learn about loops and iteration - how to repeat operations efficiently using for and while loops, and control loop execution with break and continue.
Ready to make your code repeat tasks automatically? The next lesson will show you the power of loops!