Python #2 Control & Loop

CS25C02 · COMPUTER PROGRAMMING: PYTHON

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.

08Core topics
04Practical programs
12Quiz questions
0 / 8Topics completed
YOUR LEARNING PATH

Choose a topic ๐ŸŒŸ

Study the concept, trace the example, then practise by modifying the code. All examples are beginner-friendly.

๐Ÿ”€
TOPIC 01

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 True or False.
  • 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.

⚖️
TOPIC 02

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 True or False.
  • 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.

๐Ÿช†
TOPIC 03

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 True or False.
  • 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.

๐Ÿ›ฃ️
TOPIC 04

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 True or False.
  • 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.

๐Ÿ”
TOPIC 05

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 += 1

Try changing the values and predict the output before running it in the lab below.

๐Ÿง  Exam quick notes

  • Conditions evaluate to True or False.
  • 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!”.

๐Ÿ”‚
TOPIC 06

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 True or False.
  • 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.

๐Ÿ”ณ
TOPIC 07

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 True or False.
  • 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.

⏸️
TOPIC 08

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 True or False.
  • 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.

LEARN BY DOING

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.

HANDS-ON PRACTICAL 01

Practical 1 · Pass / Fail Decision

Use if-else to classify a student mark. Try marks 39, 40, and 100.

๐Ÿ Python in browser
Ready to run
OUTPUT
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.

HANDS-ON PRACTICAL 02

Practical 2 · Grade Calculator

Use multi-way if-elif logic and validate the mark range.

๐Ÿ Python in browser
Ready to run
OUTPUT
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.

HANDS-ON PRACTICAL 03

Practical 3 · Number Analysis

Combine conditional logic with a loop to inspect a range of numbers.

๐Ÿ Python in browser
Ready to run
OUTPUT
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.

HANDS-ON PRACTICAL 04

Practical 4 · Star Pattern

Use nested loops to print a triangle. Edit the range to change its height.

๐Ÿ Python in browser
Ready to run
OUTPUT
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.

CHECK YOUR UNDERSTANDING

Unit 2 quiz ๐Ÿง 

Answer all 12 multiple-choice questions, then check your score and read the feedback.

1. Which keyword starts a conditional statement?

2. What punctuation ends an if condition line?

3. What happens when an if condition is False and there is no else?

4. Which operator gives the remainder after division?

5. In an if-elif-else chain, which branch runs?

6. Which loop is commonly used to iterate over range(5)?

7. What values are produced by range(2, 5)?

8. What must a while loop usually do to avoid running forever?

9. What does a nested loop mean?

10. What does pass do?

11. Which indentation is valid for a block?

12. For mark = 80, what is printed by if mark >= 75: print("B") elif mark >= 60: print("C")?

Submit to reveal the correct answers and explanations.

YOUR LEARNING PROGRESS

Celebrate each step ๐Ÿ†

Tick each topic after reading the notes and trying its mini task.

Unit II progress0%

๐ŸŽฏ 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.

CONTINUE LEARNING

References & learning resources ๐Ÿ“š

๐Ÿ CS25C02 · Computer Programming: PythonThink logically • Control the flow • Test the result ✨Educational study material for beginners.

Comments

Popular posts from this blog

index.html

Python #1 Fundamentals

#Python YT Videos for Jamal Engineering Students