Control Flow - If Statements
Learn how to make decisions in your code using conditional statements
Learning Objectives
- Understand the Boolean logic behind decisions
- Write if, elif, and else statements
- Use comparison and logical operators in conditions
- Understand indentation and block structure in Python
Making Decisions
In the previous lessons, our code ran from top to bottom, executing every line. Real-world programs need to make decisions: “If the user is logged in, show their dashboard; otherwise, show the login screen.”
In Python, we use the if statement to control the flow of execution.
The if Statement
The simplest form of a conditional is the if statement.
|
|
How it works:
- The condition
age >= 18is evaluated. - If it is True, the indented block of code below it is executed.
- If it is False, the indented block is skipped.
{}, Python uses indentation (usually 4 spaces) to define blocks of code. All lines indented at the same level are part of the same block.Adding else
What if you want to do something else when the condition is False? Use the else statement.
|
|
Multiple Conditions with elif
When you have more than two possibilities, use elif (short for “else if”).
|
|
Python evaluates these from top to bottom. As soon as one condition is True, its block runs, and the rest are skipped.
Logical Operators
You can combine multiple conditions using logical operators:
and: True if both conditions are True.or: True if at least one condition is True.not: Inverts the result (True becomes False).
|
|
Nested If Statements
You can place an if statement inside another if statement.
|
|
Interactive Practice
Try writing a program that checks if a number is positive, negative, or zero.
Quiz
Complete this quiz with a minimum score of 80% to mark Day 4 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!