The Power of Control Flow
In this next section, we are moving on to some truly exciting
programming. Up to this point, we have written code one line at a time
, executing print("hello"), then
print(2 + 2), and so on , while learning about
methods👆
and
data types👆.
Now, we are going to unlock the true power of programming by using loops and conditional logic. You will learn how to automate repetitive tasks, use breaks to stop a process, and skip specific lines of code entirely , based on rules you define.
Conditional Logic: Booleans, True and False
Booleans are one of the most important concepts in programming because they allow us to execute code based on a condition. The answer is always one of two things: True or False.
For example, imagine a variable called is_student. If
is_student is set to True, we can use that
to trigger specific code , like printing a welcome message:
The Two Rules You Must Never Forget
Python doesn't use curly braces {} to mark the beginning
and end of a code block. Instead, Python relies entirely on two
things:
-
The colon
:at the end of yourifstatement , this signals to Python that a block of code is coming. - Indentation (4 spaces or one tab) , this tells Python which lines belong inside that block.
To understand why indentation matters so much, you need to understand
how Python's interpreter reads your code. It works through your file
line by line, top to bottom. When it hits an
if statement followed by a colon, it asks:
"Which lines are my instructions?" , and it answers that
question entirely by looking at indentation.
Any line that is indented after the colon is
considered inside the block and will only run if the
condition is True. The moment the interpreter encounters
a line that is
back at the original indentation level, it knows the
block is over , and that line will always run,
regardless of the condition.
A single misplaced space can crash your program or, worse, silently change what it does , so indentation is never optional in Python.
Try it yourself , run the code below, then change
is_student to False and run it again to see
exactly which lines are affected.
if / else
An if statement alone only handles one outcome, what
happens when the condition is True. But what about when
it's False? That's where else comes in.
Think of it as a two-way road. Python checks the condition, if it's
True, it takes the first road. If it's
False, it takes the second. One of the two blocks will
always run.
Using the same is_student example, we can now handle both
outcomes:
Notice that else follows the exact same rules, it ends
with a colon : and its code block must
be indentedNote: else does not need a condition. A common
mistake is writing else False: which will cause an
error. else simply means "in every other case.".
Try it yourself: run the code below, then toggle
is_student between True and
False
to see both paths in action.
elif
So far our code has handled two outcomes: True or False.
But what if you need to check more than one condition? That is where
elif comes in. Short for "else if", it lets you chain multiple
conditions together. Python checks each one in order and runs the first
block that evaluates to True.
Try changing is_student and is_enrolled to see all four possible outcomes:
True, TrueTrue, FalseFalse, TrueFalse, False
We can also combine conditions inside a single if statement
using the andThere is also an keyword. When using or keyword coming up soon!and, both
conditions must be True for the block to run. If either one
is False, the whole expression is False.
As a general rule, a conditional block is structured like this: one
if to start, one or more elif blocks to handle
additional conditions, and one else at the end as the
catch-all. Python works through them in order and stops at the first
one that is True.
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named conditional_logic.py in your part38 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: Basic if/else
-
Task: Create a variable
is_logged_in = False. -
Goal: Write an
if/elseblock that prints"Welcome back!"if the user is logged in, and"Please log in to continue."if they are not. Test both outcomes.
Exercise 2: elif Chain
-
Task: Create a variable
score = 72. -
Goal: Write a conditional block that prints
"A"if the score is 90 or above,"B"if it is 80 or above,"C"if it is 70 or above, and"Failed"for anything below. Test by changing the score value.
Exercise 3: The and Keyword
-
Task: Create two variables
has_ticket = Trueandis_over_18 = False. -
Goal: Write a conditional block using
andthat prints"Entry granted."only if both conditions areTrue. If either isFalse, print"Entry denied."Test all four combinations of True and False.
Exercise 4: Real World Logic
-
Task: Create two variables
is_member = Trueandhas_paid = False. -
Goal: Write a block with
if,elif, andelsethat prints"Full access granted."if both areTrue,"Payment required."if they are a member but have not paid,"Please sign up."if they have paid but are not a member, and"No access."if neither isTrue.
Exercise 5: Spot the Bug
- Task: The following code has two errors. Find and fix them:
-
is_admin = True
if is_admin
print("Welcome, admin.")
else:
print("Access denied.") - Goal: Correct the errors and explain in a comment why each one caused a problem.
Don't Forget to commit and Push!