Making Decisions with Conditions

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
Loading interactive component...

Basic If Statements

The simplest conditional statement is the if statement:

Loading Python runtime...

Key Points:

  • The condition must evaluate to True or False
  • 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:

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than3 < 5True
>Greater than5 > 3True
<=Less than or equal3 <= 3True
>=Greater than or equal5 >= 5True

Loading Python runtime...

Logical Operators

Combine multiple conditions using logical operators:

OperatorMeaningExampleWhen True
andBoth conditions truea and bBoth a AND b are true
orAt least one truea or bEither a OR b (or both) is true
notOppositenot aa 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!