Answers for Python January 2022 QP
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.
Tip: mark sections as reviewed as you revise them. Your progress is saved in this browser.
Quick answers
Ten concise answers for the 2-mark section.
Write an algorithm to accept two numbers, compute the sum and print the result.
- Start.
- Read two numbers
aandb. - Calculate
sum = a + b. - Print
sum. - Stop.
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Sum =", a + b)Define an iterative statement.
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.
for number in range(3):
print(number) # 0, 1, 2Are comments executable statements in Python? How are comments included?
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).
# Calculate the area of a rectangle
area = length * widthIdentify the operands and operator: sum = a + b.
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.
Name the two types of iterative statements supported by Python.
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.
Define a recursive function.
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.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1)How are values in a list accessed? Must all elements have the same data type?
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.
items = [10, "Python", 3.5]
print(items[0]) # 10
print(items[-1]) # 3.5How do Python dictionaries store data? Give an example.
A dictionary stores data as key–value pairs. Keys must be unique and hashable; values may be of different types.
student = {"name": "Ravi", "mark": 92}
print(student["name"]) # RaviWrite the syntax for opening a file to write in binary mode.
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:
with open("filename.bin", "wb") as file:
file.write(b"Hello")What are the different modules in Python?
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.
import math
print(math.sqrt(25)) # 5.0Long-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.
(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.
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.
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)Initialize i = 1 and total = 0. Repeatedly add i to total while i ≤ 100, increasing i by one each time. Print the total, 5050.
total = 0
for i in range(1, 101):
total += i
print("Sum =", total) # Sum = 5050State the Towers of Hanoi problem. Outline a solution with relevant diagrams.
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:
- Move only one disk at a time.
- Only the top disk of a peg can be moved.
- A larger disk must never be placed on a smaller disk.
Recursive strategy to move n disks from source to destination using auxiliary:
- Move
n − 1disks from source to auxiliary, using destination. - Move the largest remaining disk from source to destination.
- Move the
n − 1disks from auxiliary to destination, using source.
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")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 | Disk | From | To |
|---|---|---|---|
| 1 | 1 | A | C |
| 2 | 2 | A | B |
| 3 | 1 | C | B |
| 4 | 3 | A | C |
| 5 | 1 | B | A |
| 6 | 2 | B | C |
| 7 | 1 | A | C |
Question 12 · Python data types and operators
Core building blocks of Python expressions and data.
Outline the data types supported by Python with an example.
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:
| Category | Type(s) | Example | Purpose |
|---|---|---|---|
| Numeric | int | age = 18 | Whole numbers |
| Numeric | float | height = 1.72 | Decimal numbers |
| Numeric | complex | z = 2 + 3j | Complex numbers |
| Boolean | bool | passed = True | Truth values |
| Text | str | name = "Meena" | Unicode text |
| Sequence | list | marks = [70, 82, 91] | Ordered, mutable collection |
| Sequence | tuple | point = (4, 7) | Ordered, immutable collection |
| Sequence | range | r = range(5) | Integer sequence iterator support |
| Mapping | dict | student = {"id": 4} | Key–value mapping |
| Set | set | colors = {"red", "blue"} | Unique, unordered elements |
| Set | frozenset | fs = frozenset({1, 2}) | Immutable set |
| Binary | bytes | raw = b"ABC" | Immutable bytes |
| Binary | bytearray | raw = bytearray(3) | Mutable bytes |
| Binary | memoryview | mv = memoryview(b"ABC") | View into binary data |
| Null | NoneType | result = None | Absence of a value |
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__)Name the types of operators supported by Python and outline any two with an example.
Python supports the following major operator categories:
| Category | Operators | Example / meaning |
|---|---|---|
| Arithmetic | + - * / // % ** | 7 // 2 gives 3 |
| Comparison | == != > < >= <= | 5 > 2 gives True |
| Assignment | = += -= *= /= //= %= **= etc. | x += 2 updates x |
| Logical | and or not | age >= 18 and citizen |
| Bitwise | & | ^ ~ << >> | 5 & 3 gives 1 |
| Membership | in, not in | "p" in "python" |
| Identity | is, is not | Tests whether two references identify the same object |
Arithmetic operators perform mathematical operations such as addition, subtraction, multiplication, true division, floor division, remainder and exponentiation.
a, b = 7, 2
print(a + b) # 9
print(a / b) # 3.5
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 49Comparison operators compare values and return a Boolean result (True or False).
x, y = 10, 5
print(x > y) # True
print(x == y) # False
print(x != y) # TrueLogical 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.
Outline the conditional branching statements in Python with an example.
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.
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")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")if–elif–else ladder, conditions are tested from top to bottom. Arrange ranges carefully so each value reaches the intended branch.(i) Explain while loop, break and continue with an example. (ii) Write a function to find the sum of the first n odd numbers.
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.
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.
The first n odd numbers are 1, 3, 5, …, (2n − 1). The sum is n². A loop-based function is:
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 = 16return 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.
Name the operations that can be performed on a list and outline any four with an example.
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.
# 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)| Operation | Use |
|---|---|
| Indexing / slicing | Read one element or a sublist. |
append(), extend(), insert() | Add elements. |
| Assignment | Change an element at an index. |
remove(), pop(), del | Delete an element or slice. |
+, * | Concatenate or repeat lists. |
sort(), reverse() | Reorder the list in place. |
in, len(), iteration | Membership, length, and traversal. |
(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.
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
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 NameErrordel first[0] is invalid and raises TypeError. The del statement can remove the variable binding for the whole tuple.Use sorted() with a key function that returns each item’s value, and set reverse=True.
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 76If a new dictionary in that order is needed (Python 3.7+ preserves insertion order), use:
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.
Name the different access modes for opening a file and outline them.
The mode passed to open() determines whether a file is read, written, appended, created, treated as text or treated as binary.
| Mode | Meaning | Notes |
|---|---|---|
r | Read text | Default mode; file must exist. |
w | Write text | Creates a file or truncates an existing file. |
a | Append text | Writes at the end; creates the file if absent. |
x | Exclusive creation | Fails if the file already exists. |
b | Binary modifier | Used with other modes, e.g. rb, wb. |
t | Text modifier | Default; e.g. rt. |
+ | Update modifier | Allows both reading and writing. |
r+ | Read and write | File must exist; does not truncate automatically. |
w+ | Write and read | Creates or truncates the file. |
a+ | Append and read | Writes are directed to the end of the file. |
x+ | Create, read and write | Fails if the file exists. |
# 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")with open(...) whenever possible. It closes the file automatically, even if an exception occurs. Add encoding="utf-8" for predictable text-file handling.(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.
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 thetryblock raises no exception.finally: runs whether or not an exception occurs; useful for cleanup.raise: deliberately raises an exception.
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.")except: unless there is a strong reason, because it can hide programming errors and system-exit signals.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.
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.
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.
Comments
Post a Comment