Skip to main content
Chapter 4 of 8
~26 min read
Last reviewed July 17, 2026

Control Structures in Python

Decision-making statements, while and for loops, Python lists, useful Python libraries, and techniques for testing and debugging code.

Written and reviewed by the IK Learning team

  • if / if-else / Nested
  • While & For Loops
  • Python Lists
  • Python Libraries
  • Testing & Debugging
  • Programs

This chapter builds on Python fundamentals with control structures, covering if/if-else/nested conditionals, while and for loops, working with Python lists, using built-in libraries, and testing and debugging techniques for writing reliable code.

Chapter Introduction

What this chapter is about, and why it matters

Control structures are what turn a list of instructions into a program that can make decisions and repeat work. Everything a computer does reduces to three shapes: sequence (do this, then this), selection (choose a path) and iteration (repeat while something holds). You met all three as flowchart symbols in Class 9; this chapter writes them in Python.

Lists arrive in the same chapter because loops and lists belong together. A loop without a list repeats a fixed number of times; a loop over a list processes real data of any size with the same three lines of code.

The debugging section is not filler. Professional programmers spend more time reading and fixing code than writing it, and the exam rewards students who can trace a program and say what it produces rather than only writing new code.

What You Will Learn

The skills this chapter is assessed on

  • Write if, if-else and nested conditional statements with correct indentation.
  • Choose correctly between a while loop and a for loop for a given task.
  • Create, index, modify and iterate over a Python list.
  • Import and use functions from Python libraries.
  • Trace a program by hand and identify syntax, runtime and logic errors.

Key Concepts Explained

8 core ideas — each with its definition and a separate worked example

Selection (if / if-else)

Definition

Selection is a control structure that allows a program to choose between different sets of instructions depending on whether a condition evaluates to True or False.

Example

Deciding a pass or fail result:

marks = int(input("Enter marks: "))

if marks >= 40:
    print("Pass")
else:
    print("Fail")

Detailed Explanation

The colon at the end of the if line and the indentation beneath it are both required. Python uses indentation instead of braces to decide what belongs inside the block, so indentation is grammar here, not neatness.

Nested and chained conditions (elif)

Definition

Conditions can be chained with elif so that several mutually exclusive cases are tested in order, or nested inside one another so that a second condition is only tested when the first is satisfied.

Example

Awarding a grade from a mark:

if marks >= 80:
    grade = "A"
elif marks >= 70:
    grade = "B"
elif marks >= 60:
    grade = "C"
else:
    grade = "F"

Detailed Explanation

Order matters enormously. Python stops at the first condition that is True, which is why the highest boundary must be tested first. Reverse this chain and every mark above 60 is graded "C", with no error message to warn you.

While loop

Definition

A while loop repeatedly executes a block of statements for as long as its condition remains True, testing the condition before each repetition.

Example

Counting from 1 to 5:

count = 1
while count <= 5:
    print(count)
    count = count + 1

Detailed Explanation

Use a while loop when you do not know in advance how many repetitions are needed — "keep asking until the user enters a valid password". The line that changes the loop variable is what eventually ends it; omit it and the loop runs forever.

For loop

Definition

A for loop repeats a block of statements once for each item in a sequence, such as a list or a range of numbers.

Example

The same count, and a loop over real data:

for i in range(1, 6):
    print(i)              # prints 1 2 3 4 5

subjects = ["Maths", "English", "Computer"]
for subject in subjects:
    print(subject)

Detailed Explanation

range(1, 6) stops before 6 — the end value is excluded. This off-by-one behaviour is deliberate and consistent, but it is the single most common source of loop errors, so check the boundary every time.

Python list

Definition

A list is an ordered, changeable collection that stores multiple values in a single variable, with each item accessible by its index position starting at 0.

Example

Creating, reading and modifying a list:

marks = [85, 72, 90, 66]

print(marks[0])      # 85  — the FIRST item
print(marks[-1])     # 66  — the last item
print(len(marks))    # 4

marks.append(78)     # add to the end
marks[1] = 75        # change an existing item

Detailed Explanation

Indexing from 0 means the last valid index of a four-item list is 3, not 4. Asking for marks[4] raises an IndexError. Using len(marks) rather than a hard-coded number keeps code correct when the list grows.

Python libraries

Definition

A library is a collection of pre-written code that provides ready-made functions, so that common tasks do not have to be programmed from scratch. Libraries are brought into a program with the import statement.

Example

Using the built-in math and random libraries:

import math
import random

print(math.sqrt(64))          # 8.0
print(math.pi)                # 3.14159...
print(random.randint(1, 6))   # a random dice roll

Detailed Explanation

Libraries are the practical reason Python is used so widely. Writing a square-root function correctly is a real piece of work; importing one that thousands of people have already tested takes one line and is more reliable.

Types of programming error

Definition

A syntax error breaks the grammatical rules of the language and stops the program from running at all. A runtime error occurs while the program is running and causes it to stop. A logic error lets the program run to completion but produces the wrong result.

Example

Syntax error: `if x > 5` with no colon — Python refuses to run. Runtime error: dividing by a variable that happens to be 0 — the program crashes mid-run. Logic error: writing `average = a + b / 2` instead of `(a + b) / 2` — it runs perfectly and gives the wrong number.

Detailed Explanation

Logic errors are the dangerous category precisely because nothing complains. The computer did what you wrote rather than what you meant, and only testing with values whose correct answer you already know will expose it.

Testing and debugging

Definition

Testing is the process of running a program with chosen inputs to check that its output is correct. Debugging is the process of locating and correcting the cause of an error that testing has revealed.

Example

To test a grade program, choose values at the boundaries rather than the middle: 39, 40, 41 around the pass mark, and 79, 80, 81 around the A grade. Boundaries are where nearly every off-by-one error hides.

Detailed Explanation

Adding a temporary print() inside a loop to display the variables is the simplest and most effective debugging technique there is. Seeing the actual values usually makes the mistake obvious within seconds.

Step-by-Step Worked Examples

How to lay the answer out so method marks are earned

Finding the largest value in a list

Question: Write a Python program that finds and displays the largest number in a list, without using the built-in max() function.

  1. Assume the first item is the largest so far, and store it in a variable.
  2. Loop through every item in the list.
  3. Compare each item with the current largest.
  4. If the item is bigger, replace the current largest with it.
  5. After the loop finishes, display the stored value.

Answer

numbers = [45, 88, 23, 91, 67] largest = numbers[0] for n in numbers: if n > largest: largest = n print("Largest:", largest) Starting from numbers[0] rather than 0 matters: if every value in the list were negative, starting from 0 would give the wrong answer.

Tracing a while loop by hand

Question: State exactly what the following prints: `x = 3` then `while x > 0:` `print(x)` `x = x - 1`

  1. x starts at 3. Condition 3 > 0 is True, so the loop body runs.
  2. Print 3, then x becomes 2.
  3. Condition 2 > 0 is True. Print 2, then x becomes 1.
  4. Condition 1 > 0 is True. Print 1, then x becomes 0.
  5. Condition 0 > 0 is False, so the loop ends without printing again.

Answer

The output is 3, 2, 1 on separate lines. Trace tables like this are frequently examined — write the variable value after every pass rather than trying to hold it in your head.

Where This Is Used in Real Life

The same ideas, outside the syllabus

Loops and lists behind everyday screens

Every scrolling feed is a loop over a list. The app receives a list of items and repeats the same display code for each one, which is why a feed of ten posts and a feed of ten thousand need identical code.

Validation loops

A login form that keeps asking until the input is valid is a while loop with a condition on the input. The same pattern protects a program from crashing on unexpected data.

Why professionals test at boundaries

Real systems fail at edges — the last day of a month, the empty list, the maximum allowed value. Choosing test values at boundaries rather than comfortable middles is a habit that transfers directly from this chapter to any programming work.

Common Mistakes to Avoid

Errors that cost marks in this chapter, and the correction for each

Mistake

Forgetting the colon at the end of an if, while or for line.

Correct Approach

Every line that opens a block ends with a colon, and the block beneath it is indented. Missing either is a syntax error.

Mistake

Writing an infinite loop by never changing the loop variable.

Correct Approach

A while loop needs something inside it that moves the condition towards False — usually a counter increment.

Mistake

Expecting range(1, 5) to include 5.

Correct Approach

range stops before the end value, so range(1, 5) gives 1, 2, 3, 4. Use range(1, 6) to reach 5.

Mistake

Accessing a list index that does not exist.

Correct Approach

Indexes start at 0, so a list of 4 items has indexes 0 to 3. Use len() rather than a fixed number to stay within range.

Mistake

Ordering elif conditions from lowest to highest.

Correct Approach

Python takes the first True branch, so grade boundaries must be tested from the highest downwards.

Mistake

Assuming a program that runs without errors is correct.

Correct Approach

That only rules out syntax and runtime errors. A logic error runs perfectly and gives the wrong answer — test with values whose correct output you already know.

Mistake

Mixing tabs and spaces for indentation.

Correct Approach

Python treats them differently and raises an IndentationError. Choose one — four spaces is the convention — and use it everywhere.

Exam Preparation Tips

Technique specific to this chapter

  • For trace questions, draw a table with one column per variable and one row per loop pass. Fill it in mechanically; do not attempt it mentally.
  • When choosing a loop, say why: for when the number of repetitions is known, while when it depends on a condition. The justification often carries a mark.
  • Write indentation clearly in handwritten answers. Ambiguous indentation makes the marker guess which statements are inside the block.
  • Test your own code at boundary values before submitting — the pass mark itself, an empty list, the first and last index.
  • When asked to identify an error type, name the category (syntax, runtime or logic) AND explain the specific fault. Both halves are usually marked.

Quick Revision Summary

The whole chapter in one screen — read this the night before

  • Three control structures: sequence, selection, iteration.
  • if / elif / else — colon at the end, indented block beneath.
  • elif conditions are tested in order; put the highest boundary first.
  • while = repeat while a condition holds (unknown count).
  • for = repeat once per item in a sequence (known count).
  • range(a, b) includes a but stops before b.
  • List indexes start at 0; the last index is len(list) - 1.
  • Useful list operations: append(), len(), list[i], list[-1].
  • import brings a library in: math, random.
  • Errors: syntax (will not run), runtime (crashes), logic (wrong answer).
  • Test at boundary values, not comfortable middle values.

Glossary of Terms

Words used in this chapter, defined plainly

Condition
An expression evaluating to True or False that controls a branch or loop.
Iteration
One single pass through a loop.
Index
The position of an item in a list, counting from 0.
Infinite loop
A loop whose condition never becomes False, so it never ends.
Trace table
A table recording each variable's value after every step of a program.
Module
A file of Python code that can be imported and reused.
Boundary value
A test input at the edge of a valid range, where errors are most likely.

Practice Questions

Now test yourself on the concepts above. Collapse the answers to make it a real practice run.

Multiple Choice Questions with Explanations

10 MCQs — pick an option to check yourself, then read why the answer is right

1What is the role of the range() function in Python?

Correct answer: BCreates a sequence of numbers

The range() function creates a sequence of numbers, commonly used to control how many times a loop repeats.

2What does this code output: count=0; for i in range(2): for j in range(3): count+=1; print(count)?

Correct answer: C6

The outer loop runs 2 times and the inner loop 3 times, so count is increased 2 × 3 = 6 times.

3Which method adds an item to the end of a list in Python?

Correct answer: Bappend()

The append() method adds a single item to the end of a list.

4What do control structures accomplish in programming?

Correct answer: BManage decision-making and repetition of tasks

Control structures direct the flow of a program by handling decision-making and the repetition of tasks.

5Which statement runs code when a condition turns out false?

Correct answer: Celse

The else block runs when the if condition is False, providing the alternative path.

6How can you stop print() from adding a newline?

Correct answer: AUse end=""

Setting end="" replaces the default newline so print() does not move to a new line.

7Which library generates random numbers?

Correct answer: Crandom

The random module provides functions for generating random numbers.

8What does list.append() do?

Correct answer: BAdds an item to the end

The append() method attaches a new item to the end of the list.

9The type of testing that verifies how different parts of the code work together is called:

Correct answer: BIntegration Testing

Integration testing checks that different parts or modules of the code work correctly together.

10Which debugging technique relies on adding output statements?

Correct answer: BPrint statements

Adding print statements displays the values of variables while the program runs, helping locate bugs.

Short Questions with Answers

11 short-answer questions

The range() function generates a series of numbers and is used with a for loop to determine how many times the loop should repeat. Example: for i in range(5): repeats the loop 5 times, with i taking the values 0 to 4.
The append() method adds a new item onto the end of a list, whereas the remove() method deletes a specific item from the list. Append makes the list grow, while remove makes it shrink. Example: For mylist = [1, 2], mylist.append(3) gives [1, 2, 3], and mylist.remove(1) gives [2, 3].
Debugging is the process of locating, removing, and correcting mistakes (bugs) in a program so that it runs correctly, which makes the code more reliable and effective. Example: If print("Hello" gives a syntax error, debugging means spotting the missing closing bracket and adding it.
The range() function accepts three parameters: start, which marks where the sequence begins, stop, which marks where it ends, and step, which is the gap between the numbers. Example: range(1, 10, 2) produces the numbers 1, 3, 5, 7, 9.
List methods are built-in functions that operate on lists. Three of them are append(), which adds an item to the end of the list, insert(), which adds an item at a chosen position, and pop(), which removes the last item. Example: mylist.append(5), mylist.insert(0, 9), mylist.pop()
A library is a collection of ready-made functions and features, and the import keyword is used to bring that library into a program so its functions can be used. Example: import math allows the program to use math.sqrt(16), which gives 4.0.
Unit testing is a testing technique in which small individual parts (units) of a program are tested independently to make sure each one works as expected. It matters because it helps catch problems early. Example: Testing a function that adds two numbers by checking that add(2, 3) returns 5.
In Python, list indexes start from 0, so the third element of a list sits at index 2 and is accessed by writing that index number in square brackets. Example: For mylist = [10, 20, 30], mylist[2] gives 30.
The end parameter of print() controls what is printed after the output. By default every print() ends with a newline character, but the end parameter lets you change it to a space or any other symbol. Example: print("Hi", end=" ") prints Hi followed by a space instead of moving to the next line.
An element is accessed from a list using its index number, which shows the position of the item in the list, starting from 0 for the first element. Example: For mylist = [10, 20, 30], mylist[0] gives 10.
A list item can be changed using its index. A new value is assigned to that position. Example: mylist[1] = 50 changes the second item.

Long Questions with Detailed Answers

10 in-depth answers

Decision-Making Structure Decision making in programming lets a program pick different actions depending on conditions. This mirrors how decisions get made in real life — for example, deciding whether to carry an umbrella based on the weather. Python offers a variety of conditional statements to implement decision-making. Types of Decision-making Structure In Python, decision-making structures are control flow constructs that let a program make decisions based on conditions. These structures determine which path the code execution takes. There are three main types of decision-making structures in Python: - if Statement The if statement lets us make decisions based on conditions. If the condition holds true, it runs a block of code. In Python, indentation defines the structure block or scope of the code. Proper indentation is mandatory in Python. Incorrect indentation can trigger an error in your code (Indentation Error). Syntax of if statement: if condition: code to run if the condition is true Example: If the temperature is above 30 degrees (e.g. it is hot today), we print a message. temperature=35 if temperature>30: print("It's a hot day") Output: It's a hot day - if-else Statement The if-else statement lets us run one block of code when a condition is true and a different block when it is false. Syntax of if-else statement: if condition: code to run if the condition is true else: code to run if the condition is false Example temperature=15 if temperature>30: print("It's a hot day") else: print("It's not a hot day") Output: It's not a hot day - Nested Conditions Sometimes we need to check multiple conditions inside another condition. This is called nesting. Syntax of nested if statement: if condition 1: if condition 2: code to run if both condition 1 and condition 2 are true else: code to run if condition 1 is true but condition 2 is false else: code to run if condition 1 is false Example: If the weather is rainy and the temperature is below 15 degrees, we wear a raincoat. If it's only rainy, we carry an umbrella. If the weather isn't rainy, we simply enjoy the day. weather = "rainy" temperature = 10 if weather == "rainy": if temperature < 15: print("Wear a raincoat") else: print("Take an umbrella") else: print("Enjoy your day!") Output: Wear a raincoat Explanation: In this example, the code first checks whether the weather is rainy. If so, it then checks whether the temperature is below 15 degrees. If both conditions hold true, it prints "Wear a raincoat". If the weather is rainy but the temperature isn't below 15 degrees, it prints "Take an umbrella". If the weather isn't rainy, it prints "Enjoy your day!".
Feature | While Loop | For Loop Definition | Repeatedly runs a block of code as long as a | Runs a block of code a set number of times or once | condition holds true. | for each element in a sequence. Control | Controlled by a condition (Boolean expression). | Controlled by a sequence (like range, list, string, | | or tuple). Use Case | Used when the number of iterations isn't known | Used when the number of iterations is known or when | ahead of time. | iterating over a sequence. Syntax Example | i=0 | for i in range(1,5): | while i<5: | print(i) | print(i) | | i+=1 | Risk | Can lead to infinite loops if the condition never | Lower risk of infinite loops; iterates over a fixed | becomes False. | range or sequence. Increment/Step | Must be updated manually inside the loop (i += 1). | Handled automatically by the sequence or range() | | function. Common Uses | Repeating until a condition changes, such as | Iterating over lists, strings, or generating | waiting for user input. | sequences of numbers.
Lists: In Python, a list is a flexible data structure that holds a collection of items. Lists can be created, accessed, and modified with ease. - Creating a List A list is created by placing items inside square brackets [ ], separated by commas. Lists can hold items of different types, such as numbers, strings, or even other lists. Example: Create a list of your favorite fruits. fruits=["Mango","Apple","Banana"] print(fruits) Output: ['Mango','Apple','Banana'] Explanation: This code creates a list named fruits containing three elements and then prints it. - Accessing List Items Items in a list can be accessed by referring to their index, which starts at 0. Example: Access and print the second item in the list of fruits. fruits=["Mango","Apple","Banana"] print(fruits[1]) Output: Apple Explanation: The code sets up a list 'fruit' containing 'Mango', 'Apple', and 'Banana', then prints the second item, 'Apple', using index '1'. - Modifying a List List items can be modified by accessing them through their index and assigning a new value. Example: Change the first item in the list to "Orange" and add a new fruit "Pineapple". fruits=["Mango","Apple","Banana"] fruits[0]="Orange" fruits.append("Pineapple") print(fruits) Output: ['Orange','Apple','Banana','Pineapple'] Explanation: The code changes the first element of the fruits list to 'Orange', appends Pineapple to the end, and prints the updated list.
Python libraries improve programming efficiency by supplying built-in functions and modules that let tasks be performed quickly. Python offers an extensive standard library packed with built-in modules and data structures. Importing and Using Libraries In Python, libraries act like toolboxes full of useful tools that help solve different problems without building everything from scratch. They are essentially pre-built toolkits you can use without writing all the code yourself. Let's look at how to import and use different libraries through a few simple examples. Example: Import the random library to generate random numbers. import random number=random.randint(1,10) print("The random number is:",number) Output: The random number is: 3 Explanation: The random library helps generate random numbers, which is useful in games, simulations, or even picking a winner in a lucky draw. Example: Import the statistics library to perform statistical calculations. import statistics data=[23,45,67,89,12,44,56] mean_value=statistics.mean(data) print("The mean value is:",mean_value) Output: The mean value is: 48.0 Explanation: The statistics library is a handy tool for basic statistical calculations, such as finding the mean, median, and mode of a dataset. This is especially useful for data analysis tasks. Using these libraries saves time and effort, letting you focus on the specific problem at hand instead of reinventing the wheel.
In Python programming, testing and debugging are essential practices that help ensure code works correctly and efficiently. - Testing Testing is the process of running code with various inputs to check whether it behaves as expected. The goal is to find and fix issues before the code is used in real-world applications. a. Types of Testing i. Unit Testing: Tests individual parts of the code (like functions or classes) in isolation. Python's unittest module is commonly used for this. ii. Integration Testing: Checks how different parts of the code work together. iii. Functional Testing: Confirms that the software behaves as expected from the user's perspective. iv. Regression Testing: Makes sure new changes don't break existing functionality. b. Importance 1. Helps catch and fix issues before the code is used in real-world applications. 2. Ensures the software functions reliably and as intended. - Debugging Debugging is the process of finding and fixing errors (bugs) in code. It involves pinpointing the root cause of problems and making the necessary changes. a. Common Debugging Techniques i. Print Statements: Adding print statements to check variable values at different stages of the code. ii. Debugging Tools: Using tools like pdb (Python Debugger) to step through the code, inspect variables, and follow the flow of execution. iii. Error Messages: Reading and interpreting error messages to trace the source of the problem. b. Importance 1. Helps pinpoint the root cause of problems. 2. Ensures the program runs correctly and avoids unexpected crashes.
#Loop through numbers from 1 to 20 for num in range(1,21): if num %2!=0: #Check if the number is odd print(num) Output: 1 3 5 7 9 11 13 15 17 19
(a) Generates a list of 5 random numbers between 1 and 20. # Generates a list of 5 random numbers between 1 and 20. #Import the random library import random #Generate a list of 5 random numbers between 1 and 20 random_numbers=[random.randint(1,20)for in range(5)] #Print the generated list print("Random numbers:",random_numbers) Output: Random numbers: [12,5,19,8,16] Note: The actual numbers will differ each time the program runs, because random.randint(1, 20) generates different random values. (b) Uses the statistics library to calculate and print the mean of the generated numbers. #Import necessary libraries import random import statistics mean_value=statistics.mean(random_numbers) print("Mean of the numbers:",mean_value) Output: Random numbers: [12,5,19,8,16] Mean of the numbers: 12.0
(a) Create a list of popular Pakistani dishes dishes=["Biryani","Nihari","Karahi","Seekh Kebabs"] print("Original list:",dishes) (b) Add a new dish "Quorma" dishes.append("Quorma") (c) Change "Karahi" to "Chicken Karahi" index=dishes.index("Karahi") dishes[index]="Chicken Karahi" (d) Remove "Nihari" dishes.remove("Nihari") #Print the final updated list print("Updated list:",dishes) Output: Original list: ['Biryani', 'Nihari', 'Karahi', 'Seekh Kebabs'] Updated list: ['Biryani', 'Chicken Karahi', 'Seekh Kebabs', 'Quorma']
#Define the number of rows and columns rows=3 columns=5 #Outer loop for rows for i in range(rows): #Inner loop for columns for j in range(columns): print("*",end="")#Print '*'without newline print() #Move to the next line after each row Output: ***** ***** *****
Output (The {i*j:2d} format right-aligns each product to a width of 2, so single-digit answers have a leading space.) = = = Multiplication Table (2-3) = = = 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10 2 x 6 = 12 2 x 7 = 14 2 x 8 = 16 2 x 9 = 18 2 x 10 = 20 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15 3 x 6 = 18 3 x 7 = 21 3 x 8 = 24 3 x 9 = 27 3 x 10 = 30

Important Questions for Revision

4 high-priority questions

- if Statement: Runs a block of code only when the condition is True. Example: if temperature > 30: print("Hot day") - if-else Statement: Runs one block if True, a different block if False. Example: if temperature > 30: print("Hot") else: print("Not hot") - Nested Conditions: An if statement placed inside another if statement to check multiple conditions. Example: if weather=="rainy": if temperature<15: print("Wear raincoat") else: print("Take umbrella")
while Loop: Repeats as long as a condition stays True. Used when the number of repetitions isn't known in advance. Syntax: while condition: code Example: while number < 10: print(number); number += 1 for Loop: Repeats a fixed number of times, typically to iterate over a sequence. Syntax: for variable in sequence: code Example: for friend in ["Sami","Raza"]: print("Welcome", friend) Key Difference: Use while when the end condition is unknown; use for when iterating over a known sequence.
Creating a List: items are placed inside square brackets, separated by commas. fruits = ["Mango", "Apple", "Banana"] Accessing Items: Use the index (starts from 0). fruits[1] → Apple Modifying a List: fruits[0] = "Orange" → changes first item fruits.append("Pineapple") → adds to end fruits.remove("Apple") → removes item fruits.sort() → sorts alphabetically fruits.reverse() → reverses the list
for i in range(1, 21): if i % 2 != 0: print(i) Output: 1 3 5 7 9 11 13 15 17 19 Explanation: range(1,21) generates numbers 1 through 20. The if condition checks whether the number is not divisible by 2 (i.e., it is odd), and only then prints it.

Frequently Asked Questions

6 quick answers to common questions about this chapter

A for loop runs a set number of times or once for each item in a sequence, which is best when you already know how many repetitions you need. A while loop keeps running as long as a condition stays true, which suits situations where the number of repetitions isn't known in advance.
They're related but different. Testing is running a program with various inputs to check whether it behaves correctly and to discover if there's a problem. Debugging is the process that comes after — actually finding and fixing the cause of a bug once testing has revealed one exists.
Printing a grid of stars — like 3 rows of 5 stars each — needs one loop for the rows and another loop inside it for the columns in each row. This is a nested loop: an outer loop controlling repetition, and an inner loop doing more repetition within each outer step.
By default, Python's print() function adds a new line after every call. Setting end="" stops that newline, letting multiple print statements appear on the same line — which is exactly how patterns like rows of stars or formatted tables are built using loops.
Yes. if/if-else/nested conditions, while and for loops, Python lists, useful libraries like random and statistics, and testing/debugging techniques are all examinable topics covered through MCQs and short/long answer questions.
append() always adds a new item to the very end of a list. insert() lets you specify exactly where in the list the new item should go, by giving it a position (index) as well as the value — useful when the order of items matters.

Chapter Test

10 questions with the answers hidden — check what you actually remember

You have just read the explanations above. This checks whether they stuck. The answers stay hidden until you finish, so it is closer to exam conditions than scrolling through the notes again.

  • 10 questions, one at a time — no time limit.
  • You can move back and change an answer before submitting.
  • Afterwards you get your score, every explanation, and what to re-read.

Your score is saved in this browser only. No account, nothing sent anywhere.

Related Topics in the Other Class