All printable tests View chapter notes Take the quiz

1st Year · Computer Science

11th Class Computer Science - Chapter 2: Python Programming

Short, long, and additional questions with model answers from this chapter. Use Download PDF to print or save this page.

Short Questions

  1. Explain the purpose of using comments in Python code.

    Answer

    Comments are lines the Python interpreter does not execute. They hold explanations or notes for readers.

    A single-line comment starts with #. A multi-line comment uses triple quotes at the start and end, as in the K2 and Edhi Foundation examples.

  2. Describe the difference between integer and float data types in Python. Provide an example of each.

    Answer

    An integer (int) stores a whole number, for example age = 17. A floating-point (float) stores a decimal number, for example price = 18.99.

    Both are created by assignment; the presence of a decimal point makes the value a float.

  3. Define operator precedence and give an example of an expression where operator precedence affects the result.

    Answer

    Operator precedence is the order Python uses to evaluate operators.

    Parentheses are first, then exponentiation, then multiplication, division and modulus, then addition and subtraction.

    (3 + 2) * 4 is 20, because the sum inside parentheses is done before multiplication.

  4. How does the short-hand if-else statement differ from the regular if-else statement?

    Answer

    A regular if-else uses two indented blocks, one after if and one after else. The short-hand form is one line: action_if_true if condition else action_if_false.

    The chapter sets m to a hot-day or not-hot-day message from temperature in a single statement.

  5. Explain the use of the range() function in a for loop.

    Answer

    A for loop repeats work for each item in a sequence.

    range() creates that sequence of numbers so the loop can run a set number of times.

    The class activity uses range() to print even numbers from 2 to 10 and the first ten multiples of 3.

  6. Explain how default parameters work in Python functions.

    Answer

    A default parameter supplies a value when the caller omits that argument.

    The chapter defines greet(name = 'Student').

    greet() uses Student and greet("Umer") replaces the default.

    The function can still be reused with different inputs.

  7. Explain why modular programming is useful in Python.

    Answer

    Modular programming splits a program into smaller reusable modules. Developers can work on parts independently, reuse code, and manage complex programs more easily.

    A main() function marks the start when the script runs directly rather than when it is imported.

  8. Explain the difference between a class and an object in Python.

    Answer

    A class is a template that describes attributes and methods, like the ToyCar plan for color, size, and wheels.

    An object is one actual instance created from that class.

    car1 and car2 are two ToyCar objects, each with its own values, using the same describe() method.

  9. Why must you use int() or float() with input() when the program needs a number?

    Answer

    input() displays a prompt and stores whatever the user types as text. Arithmetic and comparisons on numbers need int or float values.

    The chapter converts age with int(input(...)) and height with float(input(...)) before printing or calculating.

  10. What is the difference between / and // in Python?

    Answer

    The / operator performs ordinary division and can give a decimal, as in 10 / 3 = 3.333.... The // operator is floor division and keeps the whole-number quotient, as in 10 // 3.

    Both are arithmetic operators listed in section 2.3.1.

  11. What is the difference between the = operator and the == operator?

    Answer

    = is an assignment operator: it stores the value on the right in the variable on the left, as in a = 10.

    == is a comparison operator: it tests whether two values are equal and returns True or False, as in the weather == "sunny" example.

  12. How does a while loop differ from a for loop in this chapter?

    Answer

    A while loop repeats as long as its condition stays true and is checked before each iteration, such as adding 1 until a number reaches 10.

    A for loop walks a sequence a known number of times, such as each name in a friends list or values from range().

  13. What do the list methods append() and remove() do?

    Answer

    append(item) adds an item at the end of a list.

    remove(item) deletes the first matching item.

    The chapter appends "Hina" to students then sorts, and later removes "Sara" from a sorted name list.

    Both methods change the list in place.

  14. Why does the chapter open files with a with statement?

    Answer

    with open(...) as file: reads or writes and then closes the file when the block ends, even if an error occurs. That frees resources.

    The example opens example.txt in "r" mode, reads content, and does not need a separate close() call.

  15. Name two types of testing described in this chapter and what each checks.

    Answer

    Unit testing checks one function or class in isolation, often with the unittest module. Integration testing checks how parts work together.

    The chapter also lists functional testing (user-facing behaviour) and regression testing (old features still work after changes).

Long Questions

  1. Evaluate the following Python expressions using operator precedence from this chapter.

    (OCR in the source dropped some operators; the numbers below are the exercise values, with *, **, and % restored from sections 2.3.1 and 2.3.6.)

    (a) (18 / 3 + 4 ** 2) - (2 * (7 - 3)) / (9 % 4)
    (b) (25 + 3.4 * 6) / (2 ** 3 + 1) - 7
    (c) (12 + 6 * (5 - 2)) ** 2 / ((4 * 2 - 7) + 10)
    (d) 45 / (2 ** 2 + 3 * 4) + 8 * (7 - 3)

    Answer

    Parentheses are evaluated first, then exponentiation **, then multiplication, division and modulus, then addition and subtraction (section 2.3.6).

    • (a) 18 / 3 is 6.0 and 4 ** 2 is 16, so the first group is 22.0. 2 * (7 - 3) is 8. 9 % 4 is 1, so 8 / 1 is 8.0. 22.0 - 8.0 equals 14.0.
    • (b) 3.4 * 6 is 20.4; 25 + 20.4 is 45.4. 2 ** 3 + 1 is 9. 45.4 / 9 is approximately 5.044. Subtract 7 to get about -1.956.
    • (c) 6 * (5 - 2) is 18; 12 + 18 is 30. 30 ** 2 is 900. (4 * 2 - 7) + 10 is 11. 900 / 11 is approximately 81.818.
    • (d) 2 ** 2 is 4 and 3 * 4 is 12, so the denominator is 16. 45 / 16 is 2.8125. 8 * (7 - 3) is 32. The sum is 34.8125.

    The scan of the book dropped some operator symbols; * , ** and % were restored from the arithmetic list in 2.3.1 so the numbers in the exercise can be evaluated.

    Write every power as ** and every remainder as %.

  2. Translating the following mathematical expressions to Python syntax.

    Answer

    Python syntax does not allow multiplication by writing a number next to a variable, and it does not use the symbols × or ^.

    Use * to multiply, / to divide (this can give a decimal, as in 10 / 3), // for floor division (10 // 3), % for remainder (10 % 3 = 1), and ** for a power (10 ** 3 = 1000).

    Parentheses have the highest precedence, so (3 + 2) * 4 is 20, not 11.

    The class activity expressions in this chapter become 10 + 3 * 2 ** 2 - 5 / 5 and (10 + 3) * (2 ** (2 - 1)) / 5.

    In the first, 2 ** 2 is 4, then 3 * 4 is 12 and 5 / 5 is 1, then 10 + 12 - 1 is 21. In the second, parentheses force 10 + 3 first (13), then 2 ** 1 (2), then 13 * 2 / 5.

    Always add parentheses when a written formula is unclear so the order matches the mathematics you intend.

  3. Translate / write in Python the exercise expressions labelled (a) and (b) in the Long Questions (the scan shows (a) … + 22) 6-2x3 and (b) 7 + 4).

    Use only operators taught in this chapter.

    Answer

    The printed exercise shows two short algebraic fragments after "Translating the following mathematical expressions to Python syntax." The scan is damaged, but the chapter still tells you how to write them.

    Juxtaposition or the letter x used as "times" must become the * operator; x itself is only a variable name.

    A power written with a superscript or with ^ becomes **. Division written as a fraction or with ÷ becomes / (or // if you need the whole-number quotient from 2.3.1).

    A remainder becomes %. So a form such as 6 - 2x/3 is written 6 - 2 * x / 3, and (x + 2) squared is (x + 2) ** 2.

    A simple sum such as 7 + 4 is already valid Python. Group mixed operations with parentheses, as the unit does with (3 + 2) * 4 evaluating to 20.

    Do not leave a blank between 2 and x to mean multiply, and do not use the assignment operator = when you only mean "equals" in a formula — comparison uses == (section 2.3.2).

  4. Explain the concept of variables in Python.

    Answer

    A variable is a named storage place in the computer's memory. You use the name to store a value, read it later, and change it while the program runs (section 2.2.1.1).

    The chapter first sets age = 71 and prints that Ahmed lived 71 years, then sets age = 60 and prints Iqbal's age. The identifier stays the same; the stored number changes.

    You create different types by assignment: an integer such as age = 17, a float such as price = 18.99, a string for text, and a boolean such as is_student = True.

    Names must begin with a letter or an underscore.

    Later characters may be letters, digits, or underscores. Names are case-sensitive, so age and Age are two variables.

    Reserved words such as for, while, and if cannot be used.

    The tidbit asks you to choose meaningful lowercase names, and to separate words with underscores, for example student_name instead of a.

    That makes programs easier to read when you return to input, operators, and functions later in the unit.

  5. Write a Python program that takes a number as input and checks whether it is positive, negative, or zero using an if-elif-else statement.

    Answer

    Read the number with input() and convert it with int(), because input() returns text (section 2.2.1.5).

    Then use the if-elif-else statement from 2.4.1.3 so the program can test several conditions in order.

    number = int(input("Enter a number: "))
    if number > 0:
        print("Positive")
    elif number < 0:
        print("Negative")
    else:
        print("Zero")

    If the first condition is true, only the first block runs. If not, Python tests the elif.

    If both tests fail, the number must be zero and the else block runs.

    This is the same pattern as the weather example: if weather == "sunny", elif weather == "rainy", else enjoy the day.

    It is also the class activity that asks you to classify a number as positive, negative, or zero.

    Comparison operators >, <, and == come from section 2.3.2 and return True or False, which the if statement uses to choose a path.

  6. Write a Python program using a while loop that prints all the odd numbers between 1 and 100. Also, count and print the total number of odd numbers.

    Answer

    A while loop repeats a block as long as its condition is true and checks that condition before every pass (section 2.4.2.1).

    To list odd numbers from 1 to 100, start a counter at 1 and another variable at 0 to count how many odds you print.

    Each time the current number is odd, print it and add one to the count. Then move to the next integer.

    Odd means the remainder after dividing by 2 is not zero; the chapter introduces % with 10 % 3 = 1.

    number = 1
    count = 0
    while number <= 100:
        if number % 2 != 0:
            print(number)
            count += 1
        number += 1
    print("Total odd numbers:", count)

    += is the addition assignment operator from 2.3.3. If you forget number += 1, the condition stays true and the loop never ends.

    The printed values are 1, 3, 5, …, 99. There are 50 odd integers in that closed range, so the final line prints 50.

    This extends the chapter example that adds 1 until a number reaches 10, and the class activity that prints evens and counts odds from 1 to 20.

Additional Questions

  1. A student installs Python but python is not recognised on the command line. Using only this chapter, what installation step was missed and why does it matter?

    Answer

    The installer box "Add Python to PATH" was not checked. PATH lets the operating system find the python program when you type it in the command line.

    The chapter says to tick that box during setup.

    Without it you can still use an IDE, but command-line runs fail until Python is added to PATH or you type the full path to the executable.

  2. Write the BMI calculation described in the class activity, including which input conversions you need and what the formula means.

    Answer

    BMI = weight / height^2 with weight in kilograms and height in metres.

    Read both values with input(), convert weight and height with float(), then compute bmi = weight / (height ** 2).

    ** is the exponentiation operator from 2.3.1.

    Print the BMI and a classification using if-elif-else (for example underweight / normal / overweight) as you do for any decision in section 2.4.1.

  3. A classmate writes print("Hello" if n % 2 == 0 else "Odd") and another writes a four-line if-else. Who is using the short-hand form, and when is each style appropriate?

    Answer

    The one-line version is the short-hand if-else from 2.4.1.3: action_if_true if condition else action_if_false. It is useful for a single value or print.

    The multi-line if-else is clearer when each branch has several statements.

    The class activity asks for both styles to test even or odd, using % 2 as in the arithmetic-operator section.

  4. Trace this chapter-style loop:

    number = 0
    while number < 10:
        print(number)
        number += 1

    What is printed, and what happens if you forget number += 1?

    Answer

    The loop prints 0 through 9, then stops when number is 10. += is the addition assignment operator from 2.3.3.

    If you omit number += 1, number stays 0, the condition number < 10 stays true, and the loop never ends.

    That is why every while loop in this unit changes the variable that the condition tests.

  5. def greet(name="Student"):
        return "Hello, " + name + "!"

    What do greet() and greet("Ali") output, and which idea from 2.5.1 does this show?

    Answer

    greet() uses the default parameter Student, so it returns Hello, Student!.

    greet("Ali") passes an argument, so it returns Hello, Ali!.

    This is defining and invoking a function with a default parameter (2.5.1.1–2.5.1.3).

    The same function is reused with different inputs, which is the reuse idea in the "Did you know" box.

  6. Why does the chapter import random, datetime, and statistics instead of writing those tools from scratch?

    Answer

    Libraries and modules are ready-made toolboxes.

    import random then random.randint(1, 10) gives a random integer.

    import datetime then datetime.datetime.now() gives the current date and time.

    import statistics then statistics.mean(data) averages a list.

    You solve the task without building the algorithm yourself, which is the point of section 2.5.2–2.5.3.

  7. You have fruits = ["Mango", "Apple", "Banana"].

    Using only list operations from 2.6.1, change the first item to "Orange", add "Pineapple", and explain what fruits[1] would print after that.

    Answer

    fruits[0] = "Orange" replaces the first item because indexing starts at 0.

    fruits.append("Pineapple") adds at the end.

    The list is then ["Orange", "Apple", "Banana", "Pineapple"].

    fruits[1] is still "Apple", the second item.

    The chapter uses this exact sequence in 2.6.1.3.

  8. A student tries students.append("Hina") on a tuple of names. What happens conceptually, and which structure should they have used?

    Answer

    Tuples are immutable (2.6.2). They can be indexed and you can read len(), but you cannot append or assign to an element.

    A list should be used when you will add, remove, sort, or reverse items — those methods are listed for lists in 2.6.1.4. Keep a tuple when the collection must stay fixed.

  9. Given fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"], what do fruits[0], fruits[-1], fruits[1:4], and fruits[-4:-1] produce, and which rules are you using?

    Answer

    Indexing is zero-based: fruits[0] is Apple. Negative indices count from the end: fruits[-1] is Elderberry.

    Slicing is sequence[start:stop:step] and stop is not included, so fruits[1:4] is Banana, Cherry, Date.

    fruits[-4:-1] is Banana, Cherry, Date.

    These are the positive and negative examples in section 2.6.3.

  10. In the ecommerce package example, what is the package, what is the module, and why does from ecommerce import products help a large project?

    Answer

    ecommerce is the package (a directory of related modules).

    products.py is a module with list_products().

    Importing that module lets main.py call products.list_products() and print Laptop, Mobile, Tablet.

    Packages organise large projects the way library shelves organise books, which is the modular-programming idea in 2.5.3 and 2.7.

  11. Using the ToyCar class in 2.8, explain the roles of __init__, self, and the describe() method when car1 = ToyCar("red", "small", 4) is created.

    Answer

    __init__ runs when an object is created and stores color, size, and wheels on that object.

    self is the instance inside the methods — car1's data, not the class itself.

    describe() returns a sentence using those attributes.

    car1 is one object; a second call such as ToyCar("blue", "large", 6) makes another object with different values from the same class template.

  12. A user types 0 for a in the chapter snippet result = 10 / a. What error occurs, which block handles it, and what is printed?

    Answer

    Dividing by zero raises ZeroDivisionError. The try block contains the division.

    The except ZeroDivisionError block runs and prints You can't divide by zero. The program does not crash.

    That is the exception-handling pattern in 2.9.1.

  13. Compare write mode "w" and append mode "a" using the As-Salaam-Alaikum example. What is in the file after both with blocks run on a new file?

    Answer

    The first with open(..., "w") creates or overwrites example.txt and writes As-Salaam-Alaikum, World, plus a newline.

    The second with open(..., "a") adds Appending new line.

    without deleting the first line.

    After both blocks the file has two lines. Using "w" again later would wipe the first line; "a" would not.

  14. A function returns the wrong total only for some inputs. Which testing type from 2.10.1.1 should you run first, and which two debugging techniques from 2.10.1.3 would you apply?

    Answer

    Start with unit testing: test that one function in isolation, for example with unittest.

    Then debug with print statements to show variable values at each step, and read the error message if Python stops.

    The chapter also names pdb to step through code. Regression testing comes later, to confirm the fix did not break old cases.