Answers for Python January 2022 QP

GE3151 Python Programming | January 2022 Solved Question Paper
JANUARY 2022 · REGULATIONS 2021

Problem Solving
with Python

Complete, exam-focused answers for GE3151 — Civil Engineering, First Semester. Review short answers, study the long-answer alternatives, and practise with copyable Python programs.

📘 Paper at a glanceSolved guide
10Part A · 2 marks each
5Part B · 16 marks each
100Total marks
2 sidesBoth OR choices covered
0 of 16 sections reviewed0%

Tip: mark sections as reviewed as you revise them. Your progress is saved in this browser.

PART A · 20 MARKS

Quick answers

Ten concise answers for the 2-mark section.

Questions 1–10
01

Write an algorithm to accept two numbers, compute the sum and print the result.

Part A · 2 marks · Algorithm
Answer
  1. Start.
  2. Read two numbers a and b.
  3. Calculate sum = a + b.
  4. Print sum.
  5. Stop.
PYTHON EXAMPLE
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Sum =", a + b)
02

Define an iterative statement.

Part A · 2 marks · Control flow
Answer

An iterative statement repeatedly executes a block of code while a condition is true or for each item in a sequence. Python’s iteration statements are while and for.

EXAMPLE
for number in range(3):
    print(number)  # 0, 1, 2
03

Are comments executable statements in Python? How are comments included?

Part A · 2 marks · Comments
Answer

No. Comments are ignored by Python and are meant to explain code to readers. A single-line comment begins with #. Triple-quoted strings are commonly used for multi-line documentation (docstrings when placed in a suitable location).

EXAMPLE
# Calculate the area of a rectangle
area = length * width
04

Identify the operands and operator: sum = a + b.

Part A · 2 marks · Expressions
Answer

a and b are the operands of the addition operation, and + is the arithmetic operator. The = symbol is the assignment operator, and sum is the variable receiving the result.

05

Name the two types of iterative statements supported by Python.

Part A · 2 marks · Loops
Answer

for loop and while loop. A for loop iterates over a sequence or iterable; a while loop repeats as long as its condition is true.

06

Define a recursive function.

Part A · 2 marks · Functions
Answer

A recursive function is a function that calls itself to solve a smaller instance of a problem. It must have a base case to stop recursion.

EXAMPLE · FACTORIAL
def factorial(n):
    if n <= 1:          # base case
        return 1
    return n * factorial(n - 1)
07

How are values in a list accessed? Must all elements have the same data type?

Part A · 2 marks · Lists
Answer

List elements are accessed by their index; indexing starts at 0, and negative indexes count from the end. No, a Python list can contain elements of different data types.

EXAMPLE
items = [10, "Python", 3.5]
print(items[0])   # 10
print(items[-1])  # 3.5
08

How do Python dictionaries store data? Give an example.

Part A · 2 marks · Dictionaries
Answer

A dictionary stores data as key–value pairs. Keys must be unique and hashable; values may be of different types.

EXAMPLE
student = {"name": "Ravi", "mark": 92}
print(student["name"])  # Ravi
09

Write the syntax for opening a file to write in binary mode.

Part A · 2 marks · File handling
Answer
SYNTAX
file = open("filename.bin", "wb")

w opens for writing (creating or truncating the file); b selects binary mode. Prefer a context manager so the file is closed automatically:

RECOMMENDED
with open("filename.bin", "wb") as file:
    file.write(b"Hello")
10

What are the different modules in Python?

Part A · 2 marks · Modules
Answer

A Python module is a file containing reusable Python code such as functions, classes and variables. Broadly, modules include built-in/standard-library modules (for example math, random, os) and user-defined modules created by programmers. Third-party modules can also be installed.

EXAMPLE
import math
print(math.sqrt(25))  # 5.0
PART B · 80 MARKS

Long-answer questions

Detailed answers with algorithms, diagrams and programs. Both sides of each OR are included.

Question 11 · Algorithms and problem solving

Choose either (a) both flowcharts, or (b) Towers of Hanoi.

16 marks
11a

(i) Draw a flowchart to accept three distinct numbers, find the greatest and print the result. (ii) Draw a flowchart to find 1 + 2 + 3 + … + 100.

Alternative A · 8 + 8 marks
(i) Greatest of three distinct numbers

Algorithm: read a, b, c; if a > b and a > c, greatest is a; otherwise compare b with c and choose the larger; print the greatest.

START
↓
Input a, b, c
↓
a > b and a > c?
↙ YES          NO ↘
greatest = a
b > c?
↙     ↘
greatest = bgreatest = c
↓
Print greatest
↓
STOP
PYTHON PROGRAM
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))

if a > b and a > c:
    greatest = a
elif b > c:
    greatest = b
else:
    greatest = c

print("Greatest =", greatest)
(ii) Sum of the series from 1 to 100

Initialize i = 1 and total = 0. Repeatedly add i to total while i ≤ 100, increasing i by one each time. Print the total, 5050.

START
↓
i = 1, total = 0
↓
i ≤ 100?
YES ↓
total = total + i
↓
i = i + 1
↺ back to condition
NO → Print total
↓
STOP
PYTHON PROGRAM
total = 0
for i in range(1, 101):
    total += i
print("Sum =", total)  # Sum = 5050
OR · Alternative B
11b

State the Towers of Hanoi problem. Outline a solution with relevant diagrams.

Alternative B · 16 marks
Problem statement

The Towers of Hanoi consists of three pegs (source A, auxiliary B and destination C) and a stack of disks of different sizes placed on peg A, largest at the bottom and smallest at the top. Move all disks from A to C under these rules:

  1. Move only one disk at a time.
  2. Only the top disk of a peg can be moved.
  3. A larger disk must never be placed on a smaller disk.
Illustration · three disks
A · Source
B · Auxiliary
C · Destination

Recursive strategy to move n disks from source to destination using auxiliary:

  1. Move n − 1 disks from source to auxiliary, using destination.
  2. Move the largest remaining disk from source to destination.
  3. Move the n − 1 disks from auxiliary to destination, using source.
RECURSIVE PYTHON SOLUTION
def hanoi(n, source, auxiliary, destination):
    if n == 1:
        print(f"Move disk 1 from {source} to {destination}")
        return
    hanoi(n - 1, source, destination, auxiliary)
    print(f"Move disk {n} from {source} to {destination}")
    hanoi(n - 1, auxiliary, source, destination)

hanoi(3, "A", "B", "C")
Minimum moves: T(n) = 2T(n − 1) + 1, with T(1) = 1. Therefore T(n) = 2ⁿ − 1. For 3 disks, the minimum is 7 moves; for 4 disks, 15 moves.
Move sequence for 3 disks
MoveDiskFromTo
11AC
22AB
31CB
43AC
51BA
62BC
71AC

Question 12 · Python data types and operators

Core building blocks of Python expressions and data.

16 marks
12a

Outline the data types supported by Python with an example.

Alternative A · 16 marks

Python is dynamically typed: a variable refers to an object, and its type need not be declared in advance. Common built-in data types include:

CategoryType(s)ExamplePurpose
Numericintage = 18Whole numbers
Numericfloatheight = 1.72Decimal numbers
Numericcomplexz = 2 + 3jComplex numbers
Booleanboolpassed = TrueTruth values
Textstrname = "Meena"Unicode text
Sequencelistmarks = [70, 82, 91]Ordered, mutable collection
Sequencetuplepoint = (4, 7)Ordered, immutable collection
Sequenceranger = range(5)Integer sequence iterator support
Mappingdictstudent = {"id": 4}Key–value mapping
Setsetcolors = {"red", "blue"}Unique, unordered elements
Setfrozensetfs = frozenset({1, 2})Immutable set
Binarybytesraw = b"ABC"Immutable bytes
Binarybytearrayraw = bytearray(3)Mutable bytes
Binarymemoryviewmv = memoryview(b"ABC")View into binary data
NullNoneTyperesult = NoneAbsence of a value
DEMONSTRATION
values = [10, 3.14, 2 + 1j, True, "Python", [1, 2], (3, 4),
          {"name": "Ravi"}, {2, 4, 6}, None]
for value in values:
    print(value, "->", type(value).__name__)
Mutable examples: lists, dictionaries, sets and bytearrays. Immutable examples: integers, floats, strings, tuples, bytes and frozensets. A tuple may contain mutable objects, but the tuple’s own item references cannot be reassigned.
OR · Alternative B
12b

Name the types of operators supported by Python and outline any two with an example.

Alternative B · 16 marks

Python supports the following major operator categories:

CategoryOperatorsExample / meaning
Arithmetic+ - * / // % **7 // 2 gives 3
Comparison== != > < >= <=5 > 2 gives True
Assignment= += -= *= /= //= %= **= etc.x += 2 updates x
Logicaland or notage >= 18 and citizen
Bitwise& | ^ ~ << >>5 & 3 gives 1
Membershipin, not in"p" in "python"
Identityis, is notTests whether two references identify the same object
1. Arithmetic operators

Arithmetic operators perform mathematical operations such as addition, subtraction, multiplication, true division, floor division, remainder and exponentiation.

EXAMPLE
a, b = 7, 2
print(a + b)   # 9
print(a / b)   # 3.5
print(a // b)  # 3
print(a % b)   # 1
print(a ** b)  # 49
2. Relational (comparison) operators

Comparison operators compare values and return a Boolean result (True or False).

EXAMPLE
x, y = 10, 5
print(x > y)   # True
print(x == y)  # False
print(x != y)  # True

Logical operators (and, or, not) combine or invert Boolean conditions. Membership operators test whether an item occurs in a collection, while identity operators test object identity, not value equality.

Question 13 · Decisions and loops

Control the path and repetition of a program.

16 marks
13a

Outline the conditional branching statements in Python with an example.

Alternative A · 16 marks

Conditional statements execute different blocks depending on whether a condition evaluates to true or false. Python uses indentation to define each block.

1. Simple if

Executes a block only when its condition is true.

2. if–else

Selects one of two alternative blocks.

3. if–elif–else

Checks multiple conditions in order; the first true branch runs.

4. Nested if

An if statement placed inside another conditional block.

Example: grade classification using if–elif–else
PYTHON PROGRAM
mark = float(input("Enter mark (0–100): "))

if mark < 0 or mark > 100:
    print("Invalid mark")
elif mark >= 90:
    print("Grade A")
elif mark >= 80:
    print("Grade B")
elif mark >= 70:
    print("Grade C")
else:
    print("Grade D")
Nested if example
PYTHON PROGRAM
age = int(input("Enter age: "))
if age >= 18:
    if age >= 21:
        print("Adult: 21 or above")
    else:
        print("Adult: 18–20")
else:
    print("Below 18")
Exam point: In an if–elif–else ladder, conditions are tested from top to bottom. Arrange ranges carefully so each value reaches the intended branch.
OR · Alternative B
13b

(i) Explain while loop, break and continue with an example. (ii) Write a function to find the sum of the first n odd numbers.

Alternative B · 12 + 4 marks
(i) while, break and continue

while repeatedly executes a block while the condition is true. break immediately exits the nearest loop. continue skips the remainder of the current iteration and goes to the next iteration.

EXAMPLE
number = 0
while number < 10:
    number += 1
    if number == 3:
        continue  # skip printing 3
    if number == 7:
        break     # stop when number reaches 7
    print(number)
# Output: 1 2 4 5 6 (each on a new line)

In this example, the loop increments number; continue skips 3, and break ends the loop before 7 is printed. Always ensure a while loop can eventually terminate.

(ii) Function to sum the first n odd numbers

The first n odd numbers are 1, 3, 5, …, (2n − 1). The sum is n². A loop-based function is:

PYTHON FUNCTION
def sum_first_n_odd(n):
    if n < 0:
        raise ValueError("n must be non-negative")
    total = 0
    for i in range(n):
        total += 2 * i + 1
    return total

n = int(input("Enter n: "))
print("Sum =", sum_first_n_odd(n))
# For n = 4: 1 + 3 + 5 + 7 = 16
A compact mathematical version is return n * n for non-negative n, because the sum of the first n positive odd integers equals n².

Question 14 · Lists, tuples and dictionaries

Working with ordered collections and key–value data.

16 marks
14a

Name the operations that can be performed on a list and outline any four with an example.

Alternative A · 16 marks

A list is an ordered, mutable collection, written using square brackets. Common operations include creation, indexing/access, slicing, traversal, concatenation, repetition, membership testing, adding, updating, deleting, sorting and reversing.

Four operations (with additional useful examples)
PYTHON EXAMPLES
# 1. Create and access
numbers = [10, 20, 30, 40]
print(numbers[1])       # 20

# 2. Slice a list
print(numbers[1:3])     # [20, 30]

# 3. Add elements
numbers.append(50)      # add at end
numbers.insert(1, 15)   # insert at index 1
numbers.extend([60, 70])# add all items from iterable

# 4. Update an element
numbers[0] = 5

# 5. Delete an element
numbers.remove(30)      # remove first matching value
last = numbers.pop()    # remove and return last item
del numbers[0]          # delete by index

# 6. Concatenate and repeat
combined = [1, 2] + [3, 4]
repeated = ["X"] * 3

# 7. Membership, sorting and reversing
print(20 in numbers)
numbers.sort()
numbers.reverse()
print(numbers)
OperationUse
Indexing / slicingRead one element or a sublist.
append(), extend(), insert()Add elements.
AssignmentChange an element at an index.
remove(), pop(), delDelete an element or slice.
+, *Concatenate or repeat lists.
sort(), reverse()Reorder the list in place.
in, len(), iterationMembership, length, and traversal.
OR · Alternative B
14b

(i) Write separate programs to illustrate create, access, concatenate and delete operations in a tuple. (ii) Create a dictionary and sort its content based on values in reverse order.

Alternative B · 10 + 6 marks
(i) Tuple operations

A tuple is an ordered, immutable sequence, usually written with parentheses. You can access items and create concatenated tuples, but you cannot change or delete an individual element.

CREATE, ACCESS, CONCATENATE AND DELETE
# Create
first = (10, 20, 30)
second = (40, 50)

# Access
print(first[0])       # 10
print(first[-1])      # 30

# Concatenate: creates a new tuple
combined = first + second
print(combined)       # (10, 20, 30, 40, 50)

# Delete the whole tuple variable
del combined
# print(combined) would raise NameError
Important: Tuples are immutable. del first[0] is invalid and raises TypeError. The del statement can remove the variable binding for the whole tuple.
(ii) Sort dictionary items by value in reverse order

Use sorted() with a key function that returns each item’s value, and set reverse=True.

PYTHON PROGRAM
marks = {"Anu": 82, "Bala": 95, "Chitra": 76, "Devi": 89}

sorted_items = sorted(marks.items(),
                      key=lambda item: item[1],
                      reverse=True)

for name, mark in sorted_items:
    print(name, mark)

# Output:
# Bala 95
# Devi 89
# Anu 82
# Chitra 76

If a new dictionary in that order is needed (Python 3.7+ preserves insertion order), use:

OPTIONAL
sorted_marks = dict(sorted(marks.items(),
                           key=lambda item: item[1],
                           reverse=True))
print(sorted_marks)

Question 15 · Files and exceptions

Reading, writing, handling errors and combining files safely.

16 marks
15a

Name the different access modes for opening a file and outline them.

Alternative A · 16 marks

The mode passed to open() determines whether a file is read, written, appended, created, treated as text or treated as binary.

ModeMeaningNotes
rRead textDefault mode; file must exist.
wWrite textCreates a file or truncates an existing file.
aAppend textWrites at the end; creates the file if absent.
xExclusive creationFails if the file already exists.
bBinary modifierUsed with other modes, e.g. rb, wb.
tText modifierDefault; e.g. rt.
+Update modifierAllows both reading and writing.
r+Read and writeFile must exist; does not truncate automatically.
w+Write and readCreates or truncates the file.
a+Append and readWrites are directed to the end of the file.
x+Create, read and writeFails if the file exists.
Examples
FILE ACCESS
# Read text
with open("notes.txt", "r", encoding="utf-8") as f:
    contents = f.read()

# Write text (overwrites existing content)
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Python programming\n")

# Append text
with open("notes.txt", "a", encoding="utf-8") as f:
    f.write("File handling example\n")

# Read/write binary data
with open("image-copy.bin", "wb") as f:
    f.write(b"ABC")
Use with open(...) whenever possible. It closes the file automatically, even if an exception occurs. Add encoding="utf-8" for predictable text-file handling.
OR · Alternative B
15b

(i) What is an exception? Explain exception handling in Python. (ii) Write a program to concatenate the contents of two user-specified files into one file.

Alternative B · 8 + 8 marks
(i) Exception and exception handling

An exception is an event or error that interrupts the normal flow of a program, such as division by zero, an invalid conversion or trying to open a missing file. Exception handling lets a program respond to expected runtime problems instead of terminating unexpectedly.

  • try: contains statements that may raise an exception.
  • except: handles a matching exception.
  • else: executes only if the try block raises no exception.
  • finally: runs whether or not an exception occurs; useful for cleanup.
  • raise: deliberately raises an exception.
EXCEPTION HANDLING EXAMPLE
try:
    numerator = float(input("Numerator: "))
    denominator = float(input("Denominator: "))
    result = numerator / denominator
except ValueError:
    print("Please enter valid numbers.")
except ZeroDivisionError:
    print("The denominator cannot be zero.")
else:
    print("Result =", result)
finally:
    print("Calculation finished.")
Catch specific exceptions where possible. Avoid a bare except: unless there is a strong reason, because it can hide programming errors and system-exit signals.
(ii) Concatenate two files into a third file

Ask the user for the names of the two source files and the destination file. Open both source files in read mode and the destination in write mode, then write the content of the first followed by the second.

COMPLETE PYTHON PROGRAM
from pathlib import Path

file1 = input("Enter first input filename: ").strip()
file2 = input("Enter second input filename: ").strip()
output_file = input("Enter output filename: ").strip()

try:
    # Read the source files before opening the output file.
    # This also avoids truncating a source if its name is reused as output.
    text1 = Path(file1).read_text(encoding="utf-8")
    text2 = Path(file2).read_text(encoding="utf-8")

    Path(output_file).write_text(text1 + text2, encoding="utf-8")
    print(f"Contents concatenated into {output_file!r}")
except FileNotFoundError as error:
    print("Input file not found:", error.filename)
except PermissionError:
    print("Permission denied while accessing a file.")
except OSError as error:
    print("File operation failed:", error)

This program concatenates the file contents exactly as stored. If the first file does not end with a newline, the second file’s first text may continue on the same line; add "\n" between the strings if a separator is required.

⚡ Quick revision quiz

Five fast questions to check the basics before the exam.

1. Which keyword skips the current loop iteration?
2. What is the minimum number of moves for 3 Towers of Hanoi disks?
3. Which Python collection is immutable?
4. What is the result of 7 // 2?
5. Which file mode opens a file for appending?

Last-minute memory sheet

Formulas and distinctions worth remembering.

🔁 Iteration vs recursion

Iteration repeats a block using a loop. Recursion solves a problem by calling the same function, and needs a base case.

📦 Mutable vs immutable

Lists, dictionaries, sets are mutable. Integers, strings and tuples are immutable (the tuple container itself cannot be changed).

➗ Key formulas

1 + … + n = n(n+1)/2. First n positive odd numbers sum to n². Hanoi moves: 2ⁿ − 1.

📂 Safe file handling

Prefer with open(path, mode, encoding="utf-8") as f: for text files and catch specific file exceptions.

Prepared as an exam-revision aid. Check your class notes for the precise presentation expected by your instructor.

Comments

Popular posts from this blog

index.html

Python #1 Fundamentals

#Python YT Videos for Jamal Engineering Students