Python #2 Control & Loop
Unit 2: Control Structures
Make decisions, repeat tasks, and control the flow of a Python program. Learn each concept with concise notes, worked examples, hands-on coding, and an instant-feedback quiz.
Choose a topic ๐
Study the concept, trace the example, then practise by modifying the code. All examples are beginner-friendly.
if Statement
Execute a block only when a condition is true.
Read notes ↗if-else Statement
Choose between two alternative paths.
Read notes ↗Nested if Statement
Place one decision inside another decision.
Read notes ↗Multi-way if-elif Statements
Select one option from several mutually exclusive conditions.
Read notes ↗while Loop
Repeat a block while a condition remains true.
Read notes ↗for Loop
Iterate through a sequence or a range of values.
Read notes ↗Nested Loops
Use a loop inside another loop to work with rows and columns.
Read notes ↗pass Statement
Use a placeholder where Python syntax requires a statement.
Read notes ↗if Statement
Execute a block only when a condition is true.
๐ Understand the idea
An if statement tests a condition. If it is True, Python executes the indented body; if it is false, the body is skipped.
Remember
Always put a colon (:) after the condition and indent the body consistently.
Worked example
age = 19
if age >= 18:
print("Eligible to vote")Try changing the values and predict the output before running it in the lab below.
๐ง Exam quick notes
- Conditions evaluate to
TrueorFalse. - Indentation defines the statements controlled by a condition or loop.
- Use meaningful variable names and test boundary cases.
- Trace the program line by line to understand the output.
✍️ Mini task
Read an integer mark and print “Pass” only when it is at least 40.
if-else Statement
Choose between two alternative paths.
๐ Understand the idea
Use if for the true branch and else for the alternative branch. Exactly one branch runs.
Remember
else has no condition of its own; align it with its matching if.
Worked example
number = 7
if number % 2 == 0:
print("Even")
else:
print("Odd")Try changing the values and predict the output before running it in the lab below.
๐ง Exam quick notes
- Conditions evaluate to
TrueorFalse. - Indentation defines the statements controlled by a condition or loop.
- Use meaningful variable names and test boundary cases.
- Trace the program line by line to understand the output.
✍️ Mini task
Check whether a given integer is positive or non-positive.
Nested if Statement
Place one decision inside another decision.
๐ Understand the idea
A nested if is useful when a second test should happen only after the first condition is satisfied.
Remember
Indentation shows which if owns each block. Avoid nesting more deeply than necessary.
Worked example
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("Show ID")
else:
print("Too young")Try changing the values and predict the output before running it in the lab below.
๐ง Exam quick notes
- Conditions evaluate to
TrueorFalse. - Indentation defines the statements controlled by a condition or loop.
- Use meaningful variable names and test boundary cases.
- Trace the program line by line to understand the output.
✍️ Mini task
Check whether a number is positive and, if so, whether it is even.
Multi-way if-elif Statements
Select one option from several mutually exclusive conditions.
๐ Understand the idea
Python checks if and then each elif from top to bottom. The first true branch runs; optional else handles all remaining cases.
Remember
Order ranges from highest to lowest when using thresholds, otherwise an earlier branch may catch the value first.
Worked example
mark = 82
if mark >= 90:
grade = "A"
elif mark >= 75:
grade = "B"
elif mark >= 60:
grade = "C"
else:
grade = "D"
print(grade)Try changing the values and predict the output before running it in the lab below.
๐ง Exam quick notes
- Conditions evaluate to
TrueorFalse. - Indentation defines the statements controlled by a condition or loop.
- Use meaningful variable names and test boundary cases.
- Trace the program line by line to understand the output.
✍️ Mini task
Convert a numeric score into grades A, B, C, or D using your own cut-offs.
while Loop
Repeat a block while a condition remains true.
๐ Understand the idea
A while loop checks its condition before every iteration. Update the loop variable so the condition eventually becomes false.
Remember
If the condition never becomes false, the loop may run forever. Check initialization and update steps.
Worked example
count = 1
while count <= 5:
print(count)
count += 1Try changing the values and predict the output before running it in the lab below.
๐ง Exam quick notes
- Conditions evaluate to
TrueorFalse. - Indentation defines the statements controlled by a condition or loop.
- Use meaningful variable names and test boundary cases.
- Trace the program line by line to understand the output.
✍️ Mini task
Print the numbers from 10 down to 1, then print “Blast off!”.
for Loop
Iterate through a sequence or a range of values.
๐ Understand the idea
A for loop takes each item from an iterable. range(start, stop) includes start but excludes stop.
Remember
Remember that the stop value in range() is not included.
Worked example
for number in range(1, 6):
print(number)
for letter in "PY":
print(letter)Try changing the values and predict the output before running it in the lab below.
๐ง Exam quick notes
- Conditions evaluate to
TrueorFalse. - Indentation defines the statements controlled by a condition or loop.
- Use meaningful variable names and test boundary cases.
- Trace the program line by line to understand the output.
✍️ Mini task
Print the first ten multiples of a number entered by the user.
Nested Loops
Use a loop inside another loop to work with rows and columns.
๐ Understand the idea
For every iteration of the outer loop, the inner loop completes all its iterations. Nested loops are useful for patterns, tables, and grids.
Remember
The inner loop repeats fully for every outer-loop iteration. Track both loop variables when tracing output.
Worked example
for row in range(1, 4):
for col in range(1, 4):
print("*", end=" ")
print()Try changing the values and predict the output before running it in the lab below.
๐ง Exam quick notes
- Conditions evaluate to
TrueorFalse. - Indentation defines the statements controlled by a condition or loop.
- Use meaningful variable names and test boundary cases.
- Trace the program line by line to understand the output.
✍️ Mini task
Print a right-angled triangle of stars with five rows.
pass Statement
Use a placeholder where Python syntax requires a statement.
๐ Understand the idea
pass does nothing when executed. It can mark an unfinished function, condition, class, or loop body while keeping the program syntactically valid.
Remember
pass is not the same as break or continue; it does not stop or skip a loop iteration.
Worked example
score = 55
if score >= 40:
pass # TODO: add pass message
else:
print("Try again")Try changing the values and predict the output before running it in the lab below.
๐ง Exam quick notes
- Conditions evaluate to
TrueorFalse. - Indentation defines the statements controlled by a condition or loop.
- Use meaningful variable names and test boundary cases.
- Trace the program line by line to understand the output.
✍️ Mini task
Create an if block for a future feature using pass, then replace pass with a print statement.
Practical task board ๐งช
Minimum three practicals are included; complete all four for stronger practice with conditional logic, loops, and patterns.
How to run: Click Run Python. On first use, the Python runtime may take a little time to load. Internet access is required. Edit the code and run it again to experiment.
Practical 1 · Pass / Fail Decision
Use if-else to classify a student mark. Try marks 39, 40, and 100.
Click “Run Python” to execute this example.
The Python runtime loads on first use and needs an internet connection. Use input() when prompted; the browser runtime supports standard Python input prompts.
Practical 2 · Grade Calculator
Use multi-way if-elif logic and validate the mark range.
Click “Run Python” to execute this example.
The Python runtime loads on first use and needs an internet connection. Use input() when prompted; the browser runtime supports standard Python input prompts.
Practical 3 · Number Analysis
Combine conditional logic with a loop to inspect a range of numbers.
Click “Run Python” to execute this example.
The Python runtime loads on first use and needs an internet connection. Use input() when prompted; the browser runtime supports standard Python input prompts.
Practical 4 · Star Pattern
Use nested loops to print a triangle. Edit the range to change its height.
Click “Run Python” to execute this example.
The Python runtime loads on first use and needs an internet connection. Use input() when prompted; the browser runtime supports standard Python input prompts.
Unit 2 quiz ๐ง
Answer all 12 multiple-choice questions, then check your score and read the feedback.
Celebrate each step ๐
Tick each topic after reading the notes and trying its mini task.
๐ฏ Learning outcomes
By the end of Unit II, you should be able to write conditional statements, construct while and for loops, use nested loops for repeated patterns, and explain the purpose of pass.
References & learning resources ๐
- Python Tutorial — More Control Flow Tools (official Python docs) ↗
- Python built-in functions and
range()— Official range reference ↗ - Python language reference — Compound statements ↗
Comments
Post a Comment