Parho

Class 10 Computer Science · Chapter 4

Control Structures in Python: questions and answers

Every short question, long question and MCQ on this chapter's free papers, each with its answer. Try one yourself first, then check.

50short questions
10long questions
0MCQs

Short questions with answers

  1. Q1 · 2 marks

    What are control structures?

    Answer

    Control structures are used to control the flow of a program based on different conditions or to repeat certain actions multiple times. They help manage decision-making and the repetition of tasks.

  2. Q2 · 2 marks

    Name the two main types of control structures.

    Answer

    The two main types are Decision making and Looping.

  3. Q3 · 2 marks

    What is decision making in programming? Give a real-life example.

    Answer

    Decision making allows the program to choose different actions based on conditions.

    Example: deciding whether to take an umbrella based on the weather situation.

  4. Q4 · 3 marks

    What is the use of the if statement? Write its syntax.

    Answer

    The if statement lets us make decisions based on conditions. If the condition is true, it runs a block of code. Syntax: if condition: code to run if the condition is true

  5. Q5 · 2 marks

    Why is indentation mandatory in Python?

    Answer

    In Python, indentation defines the structure, block or scope of the code. Incorrect indentation may cause an IndentationError.

  6. Q6 · 2 marks

    What is an IndentationError?

    Answer

    An IndentationError is the error that may occur when code is not properly indented in Python.

  7. Q7 · 3 marks

    Write a Python program that prints "It's a hot day" if the temperature is above 30.

    Answer

    temperature = 35

    if temperature > 30:

    print("It's a hot day")

    Output: It's a hot day

  8. Q8 · 3 marks

    What is the if-else statement? Write its syntax.

    Answer

    The if-else statement executes one block of code if a condition is true and another block if the condition is false. Syntax: if condition: code to run if the condition is true else: code to run if the condition is false

  9. Q9 · 2 marks

    What will be the output of the following code? temperature = 15 if temperature > 30: print("It's a hot day") else: print("It's not a hot day")

    Answer

    Output: It's not a hot day. Since 15 is not greater than 30, the else block runs.

  10. Q10 · 2 marks

    What is nesting?

    Answer

    Checking multiple conditions inside another condition is called nesting.

  11. Q11 · 3 marks

    Write the syntax of a nested if statement.

    Answer

    if condition1: if condition2: code to run if both condition1 and condition2 are true else: code to run if condition1 is true but condition2 is false else: code to run if condition1 is false

  12. Q12 · 3 marks

    Explain the nested condition example of the weather and temperature.

    Answer

    The code first checks whether the weather is rainy. If it is, it checks whether the temperature is below 15 degrees. If both are true it prints 'Wear a raincoat'. If the weather is rainy but the temperature is not below 15, it prints 'Take an umbrella'. If the weather is not rainy, it prints 'Enjoy your day!'.

  13. Q13 · 2 marks

    What is a loop? Why are loops used?

    Answer

    Loops help us repeat actions, making our code more efficient and easier to read.

  14. Q14 · 2 marks

    Name the two main types of loops in Python.

    Answer

    The two main types of loops are while loops and for loops.

  15. Q15 · 3 marks

    What is a while loop? Write its syntax.

    Answer

    A while loop runs as long as a condition is true. It checks the condition before each iteration and stops when the condition is no longer true. Syntax: while condition: code to run while the condition is true

  16. Q16 · 3 marks

    Write a Python program using a while loop to print the numbers 1 to 9.

    Answer

    number = 1 while number < 10: print(number) number += 1 The loop prints the number and adds 1 until the number reaches 10.

  17. Q17 · 3 marks

    What is a for loop? Write its syntax.

    Answer

    A for loop repeats a block of code a specific number of times. It is commonly used to iterate over a sequence (like a list, tuple, or string). Syntax: for variable in sequence: code to run for each element in the sequence

  18. Q18 · 2 marks

    Explain the use of the range() function in for loop?

    Answer

    The range() function generates a sequence of numbers, which is often used in for loops. For example, for i in range(5): print(i) prints 0, 1, 2, 3, 4.

  19. Q19 · 2 marks

    What are the three parameters of the range() function?

    Answer

    The three parameters are start, stop and step. The syntaxes are range(stop), range(start, stop) and range(start, stop, step).

  20. Q20 · 2 marks

    What is the purpose of the end parameter in print()?

    Answer

    The end statement is an optional parameter of the print() function. By default every print() ends with a newline character, but the end parameter changes what is printed at the end, for example end=" " prints on the same line.

  21. Q21 · 3 marks

    Write a for loop using range() to print the even numbers from 2 to 10 on single line.

    Answer

    for i in range(2, 11, 2):

    print(i, end=" ")

    Output: 2 4 6 8 10

  22. Q22 · 3 marks

    Write a Python program that prints the first 10 multiples of 3 using a for loop and the range() function.

    Answer

    for i in range(1, 11):

    print(3 * i)

    Output: 3 6 9 12 15 18 21 24 27 30 (each on a new line).

    Alternatively: for i in range(3, 31, 3): print(i)

  23. Q23 · 2 marks

    What are nested loops? When are they used?

    Answer

    Nested loops are loops inside other loops. For each iteration of the outer loop, the inner loop runs completely. They are used when we need to perform repetitive tasks within tasks.

  24. Q24 · 2 marks

    What is the output of the following code? print("Ayyan", end="***") print("Naveed")

    Answer

    Output: Ayyan*Naveed. The end parameter replaces the newline with *, so Naveed is printed on the same line.

  25. Q25 · 4 marks

    Write a nested loop program to print stars in a right-angled triangle pattern with 5 rows.

    Answer

    n = 5 for i in range(1, n + 1): for j in range(i): print("*", end=" ") print() The inner loop runs i times and print() starts a new line after each row. Output: * * * * * * * * * * * * * * *

  26. Q26 · 2 marks

    What is a library in Python?

    Answer

    Libraries are like toolboxes or pre-built toolkits full of useful tools that help you solve different problems without having to build everything from scratch.

  27. Q27 · 2 marks

    How do you import a library in Python?

    Answer

    A library is imported using the import keyword, for example import random or import statistics.

  28. Q28 · 3 marks

    Write a program to generate a random number between 1 and 10 using the random library.

    Answer

    import random number = random.randint(1, 10) print("The random number is:", number)

  29. Q29 · 3 marks

    Write a program to calculate the mean of the list [23, 45, 67, 89, 12, 44, 56] using the statistics library.

    Answer

    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

  30. Q30 · 2 marks

    Why should you only import the libraries you need?

    Answer

    When importing libraries, make sure to only import what you need. More libraries can be explored at docs.python.org/3/.

  31. Q31 · 4 marks

    Write a Python program that imports the random and statistics libraries. Use random to generate a list of 10 random numbers between 1 and 50. Then, use statistics to calculate and print the mean (average) of those numbers.

    Answer

    import random import statistics numbers = [] for i in range(10): numbers.append(random.randint(1, 50)) print(numbers) print("The mean is:", statistics.mean(numbers))

  32. Q32 · 2 marks

    What is a data structure?

    Answer

    A data structure refers to a particular format or method for organizing and storing data.

  33. Q33 · 2 marks

    What is a list in Python?

    Answer

    A list is a versatile data structure that can hold a collection of items. Lists can contain items of different types such as numbers, strings or even other lists.

  34. Q34 · 2 marks

    How is a list created? Give an example.

    Answer

    A list is created by placing items inside square brackets [ ], separated by commas.

    Example: fruits = ["Mango", "Apple", "Banana"]

  35. Q35 · 2 marks

    How do you access the third element in a list?

    Answer

    List items are accessed by their index, starting from 0. The third element has index 2, for example fruits[2].

  36. Q36 · 2 marks

    How can we assess an element from the list?

    Answer

    An element is accessed by referring to its index, which starts from 0. For example, print(fruits[1]) prints the second item, 'Apple'.

  37. Q37 · 2 marks

    How do you modify an existing item in a list

    Answer

    Access the item via its index and assign a new value, for example fruits[0] = "Orange" changes the first item to Orange.

  38. Q38 · 4 marks

    Imagine you are maintaining a list of your favorite books:["To Kill a Mockingbird", "1984", "The Great Gatsby", "Pride and Prejudice"]. Add the book "Alchemist", replace "1984" with "Brave New World", remove "The Great Gatsby", merge the list with ["War and Peace", "Hamlet"] and print the final list.

    Answer

    books = ["To Kill a Mockingbird", "1984", "The Great Gatsby", "Pride and Prejudice"]

    books.append("Alchemist")

    books[1] = "Brave New World"

    books.remove("The Great Gatsby")

    books = books + ["War and Peace", "Hamlet"]

    print(books)

    Output: ['To Kill a Mockingbird', 'Brave New World', 'Pride and Prejudice', 'Alchemist', 'War and Peace', 'Hamlet']

  39. Q39 · 2 marks

    What is the difference between the append and remove methods in Python lists?

    Answer

    append(item) adds an item to the end of the list, while remove(item) removes the first occurrence of an item from the list.

  40. Q40 · 3 marks

    Name three list methods and their purposes.

    Answer

    1)append(item): adds an item to the end of the list.

    2)remove(item): removes the first occurrence of an item from the list.

    3)sort(): sorts the list in ascending order. (reverse() reverses the order of the list.)

  41. Q41 · 3 marks

    What does the sort() method do? Give an example.

    Answer

    sort() sorts the list in ascending order.

    numbers = [34, 12, 89, 5, 23]

    numbers.sort()

    print(numbers)

    Output: [5, 12, 23, 34, 89]

  42. Q42 · 3 marks

    What does the reverse() method do? Give an example.

    Answer

    reverse() reverses the order of the list.

    fruits = ["Apple", "Banana", "Orange", "Mango"]

    fruits.reverse()

    print(fruits)

    Output: ['Mango', 'Orange', 'Banana', 'Apple']

  43. Q43 · 2 marks

    If an item appears more than once in a list, which occurrence does remove() delete?

    Answer

    Only the first matching item is removed. For students = ["Ahmed", "Sara", "Ali", "Hina", "Sara"], students.remove("Sara") gives ['Ahmed', 'Ali', 'Hina', 'Sara'].

  44. Q44 · 2 marks

    What is testing?

    Answer

    Testing is the process of running your code with various inputs to check if it behaves as expected. The goal is to find and fix issues before the code is used in real-world applications.

  45. Q45 · 3 marks

    Name four types of testing.

    Answer

    1)Unit Testing: tests individual parts of the code in isolation.

    2)Integration Testing: checks how different parts work together.

    3)Functional Testing: validates that the software behaves as expected from the user's perspective.

    4)Regression Testing: ensures new changes don't affect the existing functionality.

  46. Q46 · 3 marks

    What is unit testing and why is it important?

    Answer

    Unit testing tests individual parts of the code (like functions or classes) in isolation. Python's unit test module is commonly used for this. It is important because it ensures each part, such as an add function, returns correct results for various inputs before the code is used in real applications.

  47. Q47 · 2 marks

    Define debugging.

    Answer

    Debugging is the process of finding and fixing errors (bugs) in your code. It involves identifying the root cause of problems and making the necessary changes.

  48. Q48 · 3 marks

    Name three common debugging techniques.

    Answer

    1)Print Statements: adding print statements to check the values of variables at different stages of the code.

    2)Debugging Tools: using tools like pdb (Python Debugger).

    3)Error Messages: reading and interpreting error messages to locate the source of the problem.

  49. Q49 · 2 marks

    What is pdb and what is it used for?

    Answer

    pdb is the Python Debugger, a debugging tool used to step through the code, inspect variables and understand the flow of execution.

  50. Q50 · 3 marks

    What is the difference between testing and debugging?

    Answer

    Testing is running code with various inputs to check if it behaves as expected and to find issues. Debugging is finding the root cause of those errors (bugs) and fixing them.

Long questions with answers

  1. Q1 · 8 marks

    Explain the different types of decision-making statements in Python with examples for each.

    Answer

    Decision making allows a program to choose different actions based on conditions. Python provides three forms.

    1.if Statement

    Runs a block of code only if the condition is true. Indentation is mandatory (otherwise IndentationError).

    Syntax:

    if condition:

    code to run if the condition is true

    Example:

    temperature = 35

    if temperature > 30:

    print("It's a hot day")

    Output: It's a hot day

    2.if-else Statement

    Executes one block if the condition is true and another if it is false.

    Syntax:

    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

    3.Nested Conditions

    Checking multiple conditions inside another condition is called nesting.

    Syntax:

    if condition1:

    if condition2:

    code if both are true

    else:

    code if condition1 is true but condition2 is false

    else:

    code if condition1 is false

    Example:

    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

  2. Q2 · 6 marks

    Compare while loops and for loops.

    Answer

    Both are looping constructs that repeat actions, making code more efficient and easier to read.

    while loop:

    - Runs as long as a condition is true; the condition is checked before each iteration and the loop stops when it is no longer true.

    - Syntax: while condition: code

    - Needs the programmer to update the variable (e.g. number += 1), otherwise it may run forever.

    Example:

    number = 1

    while number < 10:

    print(number)

    number += 1

    Output: 1 to 9

    for loop:

    - Repeats a block of code a specific number of times and is commonly used to iterate over a sequence (list, tuple, string).

    - Syntax: for variable in sequence: code

    - Often used with range() to generate numbers.

    Example:

    friends = ["Sami", "Raza", "Moosa"]

    for friend in friends:

    print("Welcome to ", friend)

    Key difference: a while loop is condition-based, while a for loop is sequence-based. Both can be nested.

  3. Q3 · 8 marks

    Describe how to work with Python lists, including creation and modification. Provide code examples for adding items, removing items and accessing elements.

    Answer

    A list is a versatile data structure that can hold a collection of items of different types (numbers, strings or even other lists).

    1.

    Creating a list: place items inside square brackets [ ] separated by commas.

    fruits = ["Mango", "Apple", "Banana"]

    print(fruits)

    2.

    Accessing elements: use the index, which starts from 0.

    print(fruits[1])

    Output: Apple

    3.

    Modifying an item: access it by index and assign a new value.

    fruits[0] = "Orange"

    4.

    Adding items: append(item) adds an item to the end.

    fruits.append("Pineapple")

    print(fruits)

    Output: ['Orange', 'Apple', 'Banana', 'Pineapple']

    5.

    Removing items: remove(item) removes the first occurrence of the item.

    students = ["Ahmed", "Sara", "Ali", "Hina", "Sara"]

    students.remove("Sara")

    print(students)

    Output: ['Ahmed', 'Ali', 'Hina', 'Sara']

    6.

    Other operations: sort() sorts in ascending order and reverse() reverses the order.

    numbers = [34, 12, 89, 5, 23]

    numbers.sort()

    print(numbers)

    Output: [5, 12, 23, 34, 89]

  4. Q4 · 8 marks

    Explain the importance of testing and debugging in programming. Discuss different debugging techniques.

    Answer

    Importance: Testing and debugging are essential practices to ensure that code works correctly and efficiently.

    Testing is the process of running code with various inputs to check if it behaves as expected. Its goal is to find and fix issues before the code is used in real-world applications.

    Types of testing:

    - Unit Testing: tests individual parts (functions or classes) in isolation; the unit test module is commonly used.

    - Integration Testing: checks how different parts work together.

    - Functional Testing: validates that the software behaves as expected from the user's perspective.

    - Regression Testing: ensures new changes don't affect the existing functionality.

    Debugging is the process of finding and fixing errors (bugs). It involves identifying the root cause of problems and making the necessary changes.

    Debugging techniques:

    1.

    Print Statements: add print statements to check the values of variables at different stages of the code.

    2.

    Debugging Tools: use tools like pdb (Python Debugger) to step through the code, inspect variables and understand the flow of execution.

    3.

    Error Messages: read and interpret error messages to locate the source of the problem.

    Together, testing finds problems and debugging fixes them, making programs reliable.

  5. Q5 · 5 marks

    How do Python libraries enhance programming efficiency? Provide an example.

    Answer

    Python offers an extensive standard library with built-in modules and data structures. Libraries are like toolboxes or pre-built toolkits, so you can solve problems without writing all the code yourself. They save time and effort and let you focus on the specific problem rather than reinventing the wheel. Only import what you need.

    Example 1: random library

    import random

    number = random.randint(1, 10)

    print("The random number is:", number)

    Example 2: statistics library

    import statistics

    data = [23, 45, 67, 89, 12, 44, 56]

    print("The mean value is:", statistics.mean(data))

    Output: The mean value is: 48

    The statistics library performs calculations such as mean, median and mode, which is useful in data analysis.

  6. Q6 · 4 marks

    Write a Python program using a loop that prints all the odd numbers between 1 and 20.

    Answer

    Method 1 (for loop with range):

    for i in range(1, 20, 2):

    print(i)

    Method 2 (checking each number):

    for i in range(1, 21):

    if i % 2 != 0:

    print(i)

    Output: 1 3 5 7 9 11 13 15 17 19 (each on a new line).

    Explanation: range(1, 20, 2) starts at 1 and increases by a step of 2, so only odd numbers are generated.

  7. Q7 · 5 marks

    Write a Python program that performs the following tasks:(a) Generates a list of 5 random numbers between 1 and 20. (b) Uses the statistics library to calculate and print the mean of the generated numbers.

    Answer

    import random

    import statistics

    numbers = []

    for i in range(5):

    numbers.append(random.randint(1, 20))

    print("Random numbers:", numbers)

    mean_value = statistics.mean(numbers)

    print("The mean is:", mean_value)

    Explanation:

    (a)random.randint(1, 20) is called 5 times in a loop and each result is appended to the list.

    (b)statistics.mean(numbers) calculates the average of the generated numbers.

  8. Q8 · 5 marks

    Write a Python program that performs the following operations:(a) Create a list of popular Pakistani dishes: ["Biryani", "Nihari", "Karahi", "Seekh Kebabs"]. (b) Add a new dish "Quorma" to the list. (c) Change "Karahi" to "Chicken Karahi". (d) Remove "Nihari" from the list.

    Answer

    dishes = ["Biryani", "Nihari", "Karahi", "Seekh Kebabs"]

    dishes.append("Quorma")

    dishes[2] = "Chicken Karahi"

    dishes.remove("Nihari")

    print(dishes)

    Output: ['Biryani', 'Chicken Karahi', 'Seekh Kebabs', 'Quorma']

    Explanation: append() adds Quorma at the end, index 2 holds Karahi so it is replaced, and remove() deletes the first occurrence of Nihari.

  9. Q9 · 5 marks

    Write a code to print stars (asterisk) in rectangular pattern using nested loops with three rows and five columns.

    Answer

    for i in range(3):

    for j in range(5):

    print("*", end=" ")

    print()

    Output:

    * * * * *

    * * * * *

    * * * * *

    Explanation: the outer loop runs 3 times (rows). For each row the inner loop prints 5 stars on the same line using end=" ". The empty print() moves to a new line after each row.

  10. Q10 · 5 marks

    Write the output of the following code print("=== Multiplication Table (1-5) ===") for i in range(2, 4): # Outer: 1 to 5 for j in range(1, 11): # Inner: 1 to 10 print(f"{i} × {j} = {i*j:2d}", end=" ") print() # New line after each table

    Answer

    Output:

    === Multiplication Table (1-5) ===

    2 × 1 = 2 2 × 2 = 4 2 × 3 = 6 2 × 4 = 8 2 × 5 = 10 2 × 6 = 12 2 × 7 = 14 2 × 8 = 16 2 × 9 = 18 2 × 10 = 20

    3 × 1 = 3 3 × 2 = 6 3 × 3 = 9 3 × 4 = 12 3 × 5 = 15 3 × 6 = 18 3 × 7 = 21 3 × 8 = 24 3 × 9 = 27 3 × 10 = 30

    Explanation: range(2, 4) gives i = 2 and 3 only, so only the tables of 2 and 3 are printed (the heading and comment say 1-5, but the code does not print those). The inner loop runs j from 1 to 10. {i*j:2d} prints the product in a width of 2, end=" " keeps each table on one line and print() starts a new line after each table.

Test yourself on this chapter

Timed chapter tests, marked the moment you finish.

See the chapter tests

Practise with a free account

Save your scores, see which chapters need work, and keep a notebook of every question you got wrong.

Create free account