Unit 1: Python programming exercises
Fundamentals of Computer and Programming in Python Laboratory notes · PTU syllabus (PGCA1906)
On this page
- Unit summary
- Areas, volumes and quadratic roots
- Divisibility and triangle classification
- Tables, Fibonacci, factorial and digits
- Series evaluation
- Matrices: transpose and arithmetic
- Strings: vowels and palindromes
- List operations and sequential search
- Dictionary-based library record
- Range-checking and string-analysis functions
- Recursive Fibonacci and factorial
- Creating and using a module
- Rectangle, Circle and word-reversal classes
- Reading and appending a text file
- Key terms
- Quick revision
- Important questions
Unit summary
This lab practises Python through graded exercises: areas and volumes, quadratic roots, divisibility and triangle checks, tables, Fibonacci and factorial, digit counting, series, matrices, vowel counting, palindromes, list operations, sequential search, a dictionary-based library record, range-checking and string-analysis functions, recursion, modules, Rectangle and Circle classes, a word-reversal class, and reading and appending text files.
After this unit you can
- Write programs using input, operators and control structures
- Process lists, strings, matrices and dictionaries
- Write functions, recursive functions and modules
- Use classes and text files
PTU syllabus topics
- Arithmetic and geometric shape area/volume computation
- quadratic equation roots
- divisibility and triangle classification programs
- multiplication tables
- Fibonacci series
- factorial computation
- digit counting
- series evaluation
- matrix transpose and arithmetic operations
- vowel counting
- palindrome checking
- list operations (insert/delete/sort)
- sequential search
- dictionary-based library record keeping
- range-checking and string-analysis functions
- recursive Fibonacci and factorial
- module creation
- Rectangle and Circle classes with area/perimeter methods
- word-reversal class
- text file reading and appending
Topic 1
Areas, volumes and quadratic roots
pythonimport math
r = float(input("Radius: "))
print(f"Circle area {math.pi * r * r:.2f}, sphere volume {4 / 3 * math.pi * r ** 3:.2f}")
l, b, h = 5, 4, 3
print("Rectangle area", l * b, "Cuboid volume", l * b * h)
a, b, c = 1, -5, 6
d = b * b - 4 * a * c
if d > 0:
print("Real roots:", (-b + math.sqrt(d)) / (2 * a), (-b - math.sqrt(d)) / (2 * a)) # 3.0 2.0
elif d == 0:
print("Equal roots:", -b / (2 * a))
else:
print("Complex roots:", complex(-b, math.sqrt(-d)) / (2 * a), complex(-b, -math.sqrt(-d)) / (2 * a))Topic 2
Divisibility and triangle classification
pythonn = int(input("Number: "))
print("Divisible by 3 and 5" if n % 15 == 0 else "Divisible by 3" if n % 3 == 0
else "Divisible by 5" if n % 5 == 0 else "Not divisible by 3 or 5")
a, b, c = sorted(map(float, input("Three sides: ").split()))
if a + b <= c:
print("Not a triangle")
elif a == b == c:
print("Equilateral")
elif a == b or b == c:
print("Isosceles")
else:
print("Scalene")
print("Right-angled" if abs(a * a + b * b - c * c) < 1e-9 else "")Topic 3
Tables, Fibonacci, factorial and digits
pythonn = int(input("Table of: "))
for i in range(1, 11):
print(f"{n} x {i:2} = {n * i}")
a, b = 0, 1
for _ in range(10):
print(a, end=" "); a, b = b, a + b # 0 1 1 2 3 5 8 13 21 34
f = 1
for i in range(2, 8): f *= i
print("\n7! =", f) # 5040
num = 907315
print("Digits:", len(str(abs(num)))) # 6
count = 0
while num: num //= 10; count += 1 # arithmetic methodTopic 4
Series evaluation
python# 1 + 1/2 + 1/3 + ... + 1/n and 1 - x²/2! + x⁴/4! - ... (cos x)
n = 10
print(sum(1 / k for k in range(1, n + 1))) # 2.928968...
import math
x, term, total = 1.0, 1.0, 1.0
for k in range(1, 8):
term *= -x * x / ((2 * k - 1) * (2 * k))
total += term
print(total, math.cos(x)) # both 0.5403...Topic 5
Matrices: transpose and arithmetic
pythonA = [[1, 2, 3], [4, 5, 6]]
B = [[7, 8, 9], [1, 2, 3]]
T = [[A[i][j] for i in range(len(A))] for j in range(len(A[0]))] # transpose 3 x 2
S = [[A[i][j] + B[i][j] for j in range(3)] for i in range(2)] # sum
C = [[1, 2], [3, 4], [5, 6]]
P = [[sum(A[i][k] * C[k][j] for k in range(3)) for j in range(2)] for i in range(2)] # product
print(T, S, P, sep="\n") # P = [[22, 28], [49, 64]]Topic 6
Strings: vowels and palindromes
These programs practise string indexing, slicing, loops and methods such as lower().
pythons = input("Text: ")
print("Vowels:", sum(1 for ch in s.lower() if ch in "aeiou"))
clean = "".join(ch.lower() for ch in s if ch.isalnum())
print("Palindrome" if clean == clean[::-1] else "Not a palindrome") # "Madam, I'm Adam" → PalindromeExample
Palindrome check: s = input().lower(); print("Palindrome" if s == s[::-1] else "Not palindrome") — "Madam" prints Palindrome, "Python" prints Not palindrome.
Exam tip
s[::-1] reverses a string in Python.
Topic 7
List operations and sequential search
These programs practise list methods (append, insert, remove, sort) and searching with loops.
pythonmarks = [56, 78, 45, 90, 67]
marks.insert(2, 88) # insert at index 2
marks.append(72)
marks.remove(45) # delete by value
del marks[0] # delete by index
marks.sort(reverse=True)
print(marks)
def linear_search(lst, key):
for i, v in enumerate(lst):
if v == key:
return i
return -1
print(linear_search(marks, 67))Example
Sequential search: key = 90; for i, m in enumerate(marks): if m == key: print("Found at index", i); break; else: print("Not found") — the for-else prints Not found only if the loop ends without break.
Exam tip
for-else: the else runs only when the loop finishes without break.
Topic 8
Dictionary-based library record
A dictionary keyed by ISBN stores each book's title, author and copies, so lookups, updates and deletions are fast.
pythonlibrary = {}
def add_book(isbn, title, author, copies):
library[isbn] = {"title": title, "author": author, "copies": copies}
def issue(isbn):
book = library.get(isbn)
if book and book["copies"] > 0:
book["copies"] -= 1
return f"Issued: {book['title']}"
return "Not available"
add_book("978-0134685991", "Effective Java", "Joshua Bloch", 2)
add_book("978-1491946008", "Fluent Python", "Luciano Ramalho", 1)
print(issue("978-1491946008"), issue("978-1491946008"))
for isbn, b in sorted(library.items(), key=lambda kv: kv[1]["title"]):
print(isbn, b["title"], b["copies"])Example
Issuing a book: if library[isbn]["copies"] > 0: library[isbn]["copies"] -= 1 reduces available copies; if copies reach 0, the program prints 'Not available'.
Exam tip
Use dict.get(key) to avoid KeyError when an ISBN does not exist.
Topic 9
Range-checking and string-analysis functions
These programs practise writing small reusable functions with parameters, return values and docstrings.
pythondef in_range(n, low, high):
"""Return True if n lies in the closed range [low, high]."""
return low <= n <= high
def analyse(text):
return {
"upper": sum(c.isupper() for c in text),
"lower": sum(c.islower() for c in text),
"digits": sum(c.isdigit() for c in text),
"spaces": text.count(" "),
"words": len(text.split()),
}
print(in_range(7, 1, 10), analyse("SBS Ludhiana 2026 MSc IT"))Example
Counting cases: a function returns sum(c.isupper() for c in s), sum(c.islower() for c in s) — for "Hello World" it returns (2, 8).
Exam tip
Test each function with normal and edge cases (empty string, boundary values).
Topic 10
Recursive Fibonacci and factorial
These programs show recursion with a base case and compare it with iteration.
pythondef fact(n):
return 1 if n <= 1 else n * fact(n - 1)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fact(6), [fib(i) for i in range(10)])Example
Recursive Fibonacci: fib(n) = n if n < 2 else fib(n − 1) + fib(n − 2) prints 0 1 1 2 3 5 8 13 for n = 0 to 7. For large n, the recursive version is very slow — a loop or memoisation is faster.
Exam tip
Mention the recursion limit and the inefficiency of naive recursive Fibonacci in the viva.
Topic 11
Creating and using a module
This program shows how to put related functions in a separate file and import them.
python# geometry.py
import math
def circle_area(r): return math.pi * r * r
def rect_area(l, b): return l * b
if __name__ == "__main__":
print("Testing:", circle_area(1))
# main.py
import geometry as g
print(g.circle_area(3), g.rect_area(4, 5))Example
Using geometry.py: import geometry; print(geometry.circle_area(3)) prints about 28.27, and from geometry import rectangle_area imports just one function.
Exam tip
Both files must be in the same folder (or on the Python path).
Topic 12
Rectangle, Circle and word-reversal classes
pythonimport math
class Rectangle:
def __init__(self, length, breadth):
self.length, self.breadth = length, breadth
def area(self): return self.length * self.breadth
def perimeter(self): return 2 * (self.length + self.breadth)
class Circle:
def __init__(self, radius): self.radius = radius
def area(self): return math.pi * self.radius ** 2
def perimeter(self): return 2 * math.pi * self.radius
class Reverser:
def reverse_words(self, s):
return " ".join(reversed(s.split()))
print(Rectangle(4, 5).area(), round(Circle(7).perimeter(), 2))
print(Reverser().reverse_words("hello python world")) # world python helloTopic 13
Reading and appending a text file
This program shows writing, appending and reading text files safely with the with statement.
pythonwith open("diary.txt", "a", encoding="utf-8") as f: # append (creates if missing)
f.write("Completed Python lab practicals\n")
with open("diary.txt", encoding="utf-8") as f:
for no, line in enumerate(f, start=1):
print(no, line.rstrip())Example
Appending entries: each run opens diary.txt in "a" mode and adds a dated line; reading it back in "r" mode prints all entries so far, oldest first.
Exam tip
Use "a" to add without erasing, and always specify encoding="utf-8".
Key terms
- Discriminant
- b² − 4ac, deciding the nature of quadratic roots
- List comprehension
- Compact syntax building a list from an expression
- Sequential search
- Checking elements one by one for a key
- Module
- Python file imported for reuse
- Append mode
- File mode adding data at the end
Quick revision
- math module; quadratic roots by discriminant; triangle inequality.
- Loops for tables, Fibonacci, factorial, digits and series.
- Nested comprehensions for matrices; string methods for vowels and palindromes.
- List insert, append, remove, del, sort; linear search; nested dictionaries.
- Functions, recursion, modules, classes, file append and read.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.When are the roots of a quadratic equation complex?
- Q2.How do you reverse a string in Python?
- Q3.Distinguish remove() and del for lists.
- Q4.Write a list comprehension for the transpose of a matrix.
- Q5.What does if __name__ == "__main__" do in a module?
- Q6.Which file mode adds text without erasing existing content?
Long-answer questions
- Q1.Write a program to find the roots of a quadratic equation.
- Q2.Write a program to add, multiply and transpose matrices.
- Q3.Write a dictionary-based library management program.
- Q4.Write Rectangle and Circle classes with area and perimeter methods.
Stuck on this unit?
Message SBS on WhatsApp for help with Fundamentals of Computer and Programming in Python Laboratory, or to ask about studying M.Sc IT at Synetic.
