CS Pathfinder Logo CS Pathfinder

Unit 5 · Advanced Topics

Complete Python Revision and University Important Programs

This is the final revision chapter covering all 5 units with quick summaries, the top 20 most-asked university exam programs with solutions, and a quick reference cheat sheet for last-minute preparation.

Unit-wise Quick Revision

Unit 1 — Introduction to Programming & Python

  • Programming is the process of giving instructions to a computer in a language it understands.
  • Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum (1991).
  • Data Types: int, float, str, bool, list, tuple, dict, set.
  • Operators: Arithmetic (+, -, *, /, //, %, **), Relational (==, !=, >, <), Logical (and, or, not), Assignment (=, +=), Membership (in, not in).
  • Input/Output: input() reads string; print() displays output.
  • Type Conversion: int(), float(), str(), bool().
  • Keywords: 35 reserved words — if, else, elif, for, while, break, continue, pass, class, def, return, import, from, True, False, None, etc.

Unit 2 — Control Structures & Strings

  • if / if-else / if-elif-else: Conditional execution based on boolean expressions.
  • for loop: Iterates over a sequence (range, list, string, tuple).
  • while loop: Repeats as long as condition is True.
  • Loop Control: break (exit loop), continue (skip iteration), pass (no-op).
  • Lists: Mutable, ordered — append(), insert(), remove(), sort(), reverse(), slicing.
  • Tuples: Immutable, ordered — indexing, slicing.
  • Dictionary: Key-value pairs — keys(), values(), items(), get().
  • Strings: Immutable — upper(), lower(), split(), join(), strip(), replace(), find(), format().
  • String Slicing: s[start:end:step]

Unit 3 — Functions

  • def keyword: Defines a function. def func_name(params):
  • Arguments: Positional, default, keyword, *args, **kwargs.
  • Return: return sends value back; without it, function returns None.
  • Scope: Local (inside function), Global (outside), global keyword.
  • Lambda: Anonymous one-line function — lambda x: x * 2
  • Recursion: Function calls itself. Must have base case to avoid infinite recursion.
  • map(), filter(), reduce(): Functional programming tools.

Unit 4 — OOP & Advanced Concepts

  • Class & Object: Blueprint (class) vs instance (object). __init__ constructor, self parameter.
  • Encapsulation: Data hiding using private variables (__var), getters/setters.
  • Inheritance: Child inherits from parent — single, multiple, multilevel, hierarchical. super() calls parent.
  • Polymorphism: Method overriding, duck typing, operator overloading (__add__, __len__, __str__).
  • Exception Handling: try / except / else / finally, raise keyword, built-in exceptions.
  • File Handling: open(), read(), write(), close(), with statement.

Unit 5 — Advanced Topics

  • NumPy: ndarray, array(), zeros(), ones(), arange(), linspace(), shape, dtype, broadcasting.
  • Pandas: Series, DataFrame, read_csv(), head(), info(), describe(), iloc, loc, filtering.
  • Matplotlib: plot(), bar(), hist(), scatter(), pie(), title(), xlabel(), legend(), show(), savefig().
  • Inheritance & Polymorphism: Covered in OOP (Unit 4) but tested in Unit 5 exams.

Top 20 University Exam Programs

1. Fibonacci Series

Print the first N terms of the Fibonacci series.

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=" ")
        a, b = b, a + b

fibonacci(10)
# Output: 0 1 1 2 3 5 8 13 21 34

2. Factorial of a Number

def factorial(n):
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # 120

3. Prime Number Check

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(17))  # True
print(is_prime(15))  # False

4. Palindrome Check

def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]

print(is_palindrome("Madam"))   # True
print(is_palindrome("Hello"))    # False

5. Matrix Multiplication

def multiply_matrices(A, B):
    rows_A, cols_A = len(A), len(A[0])
    cols_B = len(B[0])
    result = [[0] * cols_B for _ in range(rows_A)]

    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                result[i][j] += A[i][k] * B[k][j]
    return result

A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
for row in multiply_matrices(A, B):
    print(row)
# [19, 22]
# [43, 50]

6. Sorting — Bubble Sort & Selection Sort

# Bubble Sort
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr

# Selection Sort
def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        min_idx = i
        for j in range(i+1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr

print(bubble_sort([64, 34, 25, 12, 22]))
# [12, 22, 25, 34, 64]

7. Linear Search & Binary Search

# Linear Search
def linear_search(arr, key):
    for i in range(len(arr)):
        if arr[i] == key:
            return i
    return -1

# Binary Search (sorted array)
def binary_search(arr, key):
    low, high = 0, len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == key:
            return mid
        elif arr[mid] < key:
            low = mid + 1
        else:
            high = mid - 1
    return -1

data = [10, 20, 30, 40, 50]
print(binary_search(data, 30))  # 2

8. String Reversal

# Method 1: Slicing
s = "Hello World"
print(s[::-1])  # dlroW olleH

# Method 2: Loop
def reverse_str(s):
    result = ""
    for ch in s:
        result = ch + result
    return result

print(reverse_str("Python"))  # nohtyP

9. File Word Count

def count_words(filename):
    with open(filename, "r") as f:
        text = f.read()
    words = text.split()
    print(f"Total words: {len(words)}")
    print(f"Total lines: {len(text.splitlines())}")
    print(f"Total characters: {len(text)}")

count_words("sample.txt")

10. Class and Object Program

class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def grade(self):
        if self.marks >= 90: return "A+"
        elif self.marks >= 80: return "A"
        elif self.marks >= 70: return "B"
        else: return "C"

    def display(self):
        print(f"{self.name}: {self.marks} ({self.grade()})")

s1 = Student("Amit", 92)
s2 = Student("Priya", 78)
s1.display()  # Amit: 92 (A+)
s2.display()  # Priya: 78 (B)

11. Inheritance Program

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound"

class Dog(Animal):
    def speak(self):
        return f"{self.name} barks"

class Cat(Animal):
    def speak(self):
        return f"{self.name} meows"

for a in [Dog("Buddy"), Cat("Kitty")]:
    print(a.speak())

12. Exception Handling Program

try:
    num = int(input("Enter a number: "))
    result = 100 / num
    print(f"Result: {result}")
except ValueError:
    print("Invalid input! Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("Execution completed.")

13. List Operations Program

numbers = [5, 2, 8, 1, 9, 3]

print("Original:", numbers)
numbers.append(7)
numbers.sort()
print("Sorted:", numbers)
print("Sum:", sum(numbers))
print("Max:", max(numbers))
print("Even:", [x for x in numbers if x % 2 == 0])

14. Dictionary Operations Program

student = {"name": "Amit", "age": 22, "marks": 85}

student["grade"] = "A"
del student["age"]

for key, val in student.items():
    print(f"{key}: {val}")

print("Keys:", list(student.keys()))
print("Marks:", student.get("marks", 0))

15. Function with Return Value

def calculate(a, b, op="add"):
    if op == "add": return a + b
    elif op == "sub": return a - b
    elif op == "mul": return a * b
    elif op == "div": return a / b if b != 0 else "Error"

print(calculate(10, 5, "add"))  # 15
print(calculate(10, 3, "mul"))  # 30

16. Recursion Program — Power

def power(base, exp):
    if exp == 0:
        return 1
    return base * power(base, exp - 1)

print(power(2, 5))  # 32
print(power(3, 3))  # 27

17. String Methods Program

s = "  Hello, World!  "

print(s.strip())        # "Hello, World!"
print(s.lower())        # "  hello, world!  "
print(s.upper())        # "  HELLO, WORLD!  "
print(s.replace("World", "Python"))
print(s.split(","))     # ['  Hello', ' World!  ']
print(s.count("l"))     # 3
print(s.find("World"))  # 9
print(len(s.strip()))   # 13

18. Calculator Using Functions

def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b
def div(a, b):
    if b == 0: return "Error: Division by zero"
    return a / b

print("1. Add  2. Sub  3. Mul  4. Div")
ch = input("Choice: ")
a = float(input("First: "))
b = float(input("Second: "))

ops = {"1": add, "2": sub, "3": mul, "4": div}
if ch in ops:
    print("Result:", ops[ch](a, b))
else:
    print("Invalid choice")

19. Student Record Management

students = []

def add_student():
    name = input("Name: ")
    marks = float(input("Marks: "))
    students.append({"name": name, "marks": marks})

def show_all():
    for s in students:
        print(f"{s['name']}: {s['marks']}")

def topper():
    if students:
        t = max(students, key=lambda x: x["marks"])
        print(f"Topper: {t['name']} ({t['marks']})")

# Menu-driven example
for _ in range(3):
    add_student()
show_all()
topper()

20. Basic NumPy / Pandas Program

import numpy as np
import pandas as pd

# NumPy array operations
arr = np.array([10, 20, 30, 40, 50])
print("Array:", arr)
print("Mean:", np.mean(arr))
print("Std:", np.std(arr))

# Pandas DataFrame
df = pd.DataFrame({
    "Name": ["A", "B", "C"],
    "Marks": [85, 92, 78]
})
print(df)
print(df.describe())

Quick Reference Cheat Sheet

String Methods

MethodDescription
upper() / lower()Convert to upper/lower case
strip()Remove leading/trailing whitespace
split()Split string into list
join()Join list into string
replace()Replace substring
find()Find index of substring (-1 if not found)
count()Count occurrences

List Methods

MethodDescription
append(x)Add x to end
insert(i, x)Insert x at index i
remove(x)Remove first occurrence of x
pop()Remove and return last element
sort()Sort in place
reverse()Reverse in place
index(x)Return index of first x

Dictionary Methods

MethodDescription
keys()Return all keys
values()Return all values
items()Return (key, value) pairs
get(key, default)Get value safely with default
update()Merge another dictionary
pop(key)Remove and return value

OOP Keywords

KeywordUsage
classDefine a class
selfReference to current instance
__init__Constructor (initializes attributes)
super()Call parent class methods
isinstance()Check object type
try/exceptException handling
raiseThrow a custom exception

NumPy / Pandas / Matplotlib

LibraryKey Functions
NumPyarray(), zeros(), ones(), arange(), linspace(), mean(), sum(), std()
PandasDataFrame(), read_csv(), head(), describe(), iloc[], loc[], groupby()
Matplotlibplot(), bar(), hist(), scatter(), pie(), title(), xlabel(), legend(), show()

Final Exam Strategy

  • Read all questions first — attempt the ones you are most confident about.
  • For theory questions, write definition + key points + diagram (if applicable).
  • For programs, write clean code with comments. Always show expected output.
  • Use proper variable names and indentation — presentation matters.
  • Practice writing code by hand — university exams are pen-and-paper.
  • Revise the top 20 programs above — at least 3-4 will appear in your exam.
  • Don't leave any question blank — write something relevant for partial marks.

Key Points

Cover all 5 units — basics are as important as advanced topics.

Master the top 20 programs — these are the most frequently asked in exams.

Practice writing code by hand without an IDE.

Revise cheat sheets for string, list, dict, and OOP methods.

NumPy + Pandas + Matplotlib together form the data science toolkit.

Always include comments and output in your exam answers.

Python Programming Handwritten Notes

Master Python Programming with Easy Handwritten Notes – Perfect for Interviews, Placements, GATE & Exams.