Python Programming โ€“ University Level โ€“ Pak Notes Hub
๐Ÿ University Level โ€” BS CS / BS IT

Python Programming
Complete Notes

Variables to OOP ยท Data Structures ยท File & Exception Handling โ€” All in Easy English

๐Ÿ 15 Units ๐ŸŽ“ University Level ๐Ÿ’ป Code Examples ๐Ÿ“ Practice Tasks ๐Ÿš€ Final Project
Unit 1

Introduction to Python

What is Python and why is it the world's most popular language?

What is Python?

Python is a high-level, general-purpose, interpreted programming language created by Guido van Rossum and first released in 1991. It is famous for its clean, simple syntax that reads almost like plain English, making it one of the easiest languages for beginners to learn.

๐Ÿ’ก Python is named after the British comedy show "Monty Python's Flying Circus" โ€” not the snake! Guido van Rossum was a fan of the show while creating the language.

Key Features of Python

โœ… Easy to Read & Write
โš™๏ธ Interpreted Language
๐Ÿ”„ Dynamically Typed
๐Ÿงฉ Object-Oriented
๐Ÿ†“ Free & Open Source
๐Ÿ“š Huge Standard Library
๐Ÿ’ป Cross-Platform
๐ŸŒ Large Community Support

Compiled vs Interpreted Languages

FeatureCompiled (C, C++)Interpreted (Python)
ExecutionConverted to machine code before runningExecuted line-by-line by an interpreter
SpeedGenerally fasterGenerally slower
ErrorsShown only after full compilationShown immediately, line by line
PortabilityNeeds recompiling per OSSame code runs anywhere Python is installed

Applications of Python

  • Web Development โ€” Django, Flask frameworks
  • Data Science & Machine Learning โ€” NumPy, Pandas, TensorFlow
  • Automation & Scripting โ€” automating repetitive tasks
  • Game Development โ€” Pygame library
  • Desktop GUI Apps โ€” Tkinter, PyQt
  • Cybersecurity โ€” writing security & pentesting tools
  • Artificial Intelligence โ€” the leading language for AI/ML research

Writing Your First Python Program

Python programs are saved with a .py extension and run using the Python interpreter.

# This is a comment - Python ignores this line
print("Hello, World!")

# Output:
# Hello, World!

Run it from the terminal using:

python filename.py
# or on some systems:
python3 filename.py

Python Identifiers & Keywords

An identifier is the name given to variables, functions, and classes. Python has 35 reserved keywords that cannot be used as identifiers because they carry special meaning.

CategoryExamples
ValuesTrue, False, None
Logicaland, or, not, in, is
Control Flowif, elif, else, for, while, break, continue, pass
Functions / Classesdef, return, class, lambda
Modulesimport, from, as
Error Handlingtry, except, finally, raise, with
โœ๏ธ Practice: Install Python on your computer, check the version using python --version in the terminal, and write a program that prints your name, roll number, and university on three separate lines.
Unit 2

Variables, Data Types & Type Casting

How Python stores and converts data.

What is a Variable?

A variable is a named location in memory used to store data. Unlike many other languages, Python variables do not require explicit type declaration โ€” the type is decided automatically from the value assigned.

name = "Ali"        # string
age = 20            # integer
gpa = 3.75          # float
is_pass = True      # boolean

Variable Naming Rules

  • Must start with a letter or underscore (_), not a digit
  • Can contain letters, digits, and underscores only
  • Case-sensitive โ€” age and Age are different variables
  • Cannot be a Python keyword (e.g. class, for, if)
  • Should be descriptive โ€” student_name is better than x

Python Data Types

Data TypeExampleDescription
int10, -5, 2024Whole numbers (no decimal point)
float3.14, -0.5Numbers with a decimal point
str"Hello"Sequence of characters (text)
boolTrue, FalseLogical values
list[1, 2, 3]Ordered, changeable collection
tuple(1, 2, 3)Ordered, unchangeable collection
dict{"a": 1}Key-value pairs
set{1, 2, 3}Unordered collection of unique items
NoneTypeNoneRepresents "no value"

Checking Data Type โ€” type()

Use the built-in type() function to check the data type of any variable.

x = 25
y = 3.14
z = "Python"

print(type(x))   # <class 'int'>
print(type(y))   # <class 'float'>
print(type(z))   # <class 'str'>

Type Casting (Type Conversion)

Type casting means converting a value from one data type to another โ€” either automatically (implicit) or manually (explicit).

FunctionConverts ToExample
int()Integerint("10") โ†’ 10
float()Floatfloat("3.5") โ†’ 3.5
str()Stringstr(25) โ†’ "25"
bool()Booleanbool(1) โ†’ True
list()Listlist("ab") โ†’ ['a','b']
age = "20"             # string
age = int(age)         # now an integer
print(age + 5)         # 25

price = 99
price_text = str(price)
print("Price: " + price_text)   # Price: 99

Mutable vs Immutable Types

Mutable (can be changed)Immutable (cannot be changed)
listint, float, bool
dictstr
settuple
๐Ÿ’ก "Immutable" means once a value is created, it cannot be modified in place โ€” a new object is created instead. Strings and tuples are immutable; lists and dictionaries are mutable.
โœ๏ธ Practice: Declare 5 variables of different data types (int, float, str, bool, list). Print each variable along with its type using type().
Unit 3

Operators & Expressions

Arithmetic, comparison, logical and other operators.

Arithmetic Operators

OperatorMeaningExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/Division (float)5 / 22.5
//Floor Division5 // 22
%Modulus (remainder)5 % 21
**Exponent (power)5 ** 225

Comparison (Relational) Operators

OperatorMeaningExample
==Equal to5 == 5 โ†’ True
!=Not equal to5 != 3 โ†’ True
>Greater than5 > 3 โ†’ True
<Less than5 < 3 โ†’ False
>=Greater or equal5 >= 5 โ†’ True
<=Less or equal5 <= 4 โ†’ False

Logical Operators

OperatorMeaningExample
andTrue if both conditions are True(5>2) and (3>1) โ†’ True
orTrue if at least one condition is True(5>2) or (1>3) โ†’ True
notReverses the resultnot(5>2) โ†’ False

Assignment Operators

OperatorExampleSame As
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
//=x //= 3x = x // 3

Membership & Identity Operators

OperatorUseExample
inChecks if a value exists in a sequence"a" in "cat" โ†’ True
not inChecks if a value does not exist5 not in [1,2,3] โ†’ True
isChecks if two variables point to the same objecta is b
is notChecks they do not point to the same objecta is not b

Operator Precedence

When multiple operators appear in one expression, Python follows a fixed order: Parentheses โ†’ Exponent โ†’ Multiplication/Division โ†’ Addition/Subtraction โ†’ Comparison โ†’ Logical.

result = 5 + 3 * 2      # Multiplication happens first
print(result)             # 11

result = (5 + 3) * 2     # Parentheses happen first
print(result)             # 16
โœ๏ธ Practice: Write a program that takes two numbers as input and prints the result of all arithmetic operators (+, -, *, /, //, %, **) applied to them.
Unit 4

Input, Output & String Formatting

Talking to the user โ€” print(), input() and f-strings.

The print() Function

print() displays output on the screen. It accepts multiple values separated by commas and supports useful parameters like sep and end.

print("Hello", "World")                 # Hello World
print("Hello", "World", sep="-")        # Hello-World
print("Hello", end=" ")
print("World")                          # Hello World (same line)

The input() Function

input() reads text typed by the user from the keyboard. It always returns a string โ€” even if the user types a number โ€” so numeric input must be converted using int() or float().

name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(name, "is", age, "years old")

String Formatting Methods

MethodExampleOutput
f-stringf"My name is {name}"My name is Ali
.format()"My name is {}".format(name)My name is Ali
% operator"My name is %s" % nameMy name is Ali
name = "Ayesha"
gpa = 3.85
print(f"Student: {name}, GPA: {gpa:.1f}")
# Output: Student: Ayesha, GPA: 3.9
๐Ÿ’ก f-strings (Python 3.6+) are the modern, recommended way to format strings โ€” faster and easier to read than .format() or % formatting.

Escape Sequences

Escape SequenceMeaning
\nNew line
\tTab space
\\Backslash
\'Single quote
\"Double quote
โœ๏ธ Practice: Write a program that asks the user for their name and CGPA, then prints a formatted sentence: "Welcome, <name>! Your CGPA is <value>." using an f-string.
Unit 5

Decision Making โ€” if, elif, else

Making your program take decisions.

The if Statement

The if statement runs a block of code only when a condition is True. Python uses indentation instead of curly braces to define code blocks.

marks = 85
if marks >= 50:
    print("You passed!")

if-else Statement

marks = 35
if marks >= 50:
    print("You passed!")
else:
    print("You failed.")

if-elif-else Ladder

marks = 72
if marks >= 90:
    grade = "A"
elif marks >= 80:
    grade = "B"
elif marks >= 70:
    grade = "C"
else:
    grade = "F"
print("Grade:", grade)

Nested if Statements

An if placed inside another if is called a nested if โ€” used when a decision depends on more than one condition.

age = 20
has_id = True
if age >= 18:
    if has_id:
        print("Entry allowed")
    else:
        print("ID required")
else:
    print("Too young to enter")

Ternary (Conditional) Operator

A shorter, one-line way to write a simple if-else statement.

age = 17
status = "Adult" if age >= 18 else "Minor"
print(status)     # Minor
โœ๏ธ Practice: Write a program that takes a student's marks as input and prints their grade (A, B, C, D, F) using an if-elif-else ladder.
Unit 6

Loops โ€” for & while

Repeating tasks without writing the same code again and again.

The for Loop

A for loop iterates over a sequence (list, string, range, etc.) and repeats a block of code for each item.

for i in range(1, 6):
    print(i)
# Output: 1 2 3 4 5 (each on a new line)

The range() Function

SyntaxMeaningExample
range(stop)0 to stop-1range(5) โ†’ 0,1,2,3,4
range(start, stop)start to stop-1range(2,6) โ†’ 2,3,4,5
range(start, stop, step)with custom steprange(0,10,2) โ†’ 0,2,4,6,8

The while Loop

A while loop repeats a block of code as long as a condition stays True โ€” used when you don't know in advance how many times to repeat.

count = 1
while count <= 5:
    print(count)
    count += 1

break, continue & pass

KeywordPurpose
breakImmediately exits the loop
continueSkips current iteration, moves to next
passDoes nothing โ€” a placeholder statement
for i in range(1, 10):
    if i == 5:
        break          # stop loop completely
    if i % 2 == 0:
        continue        # skip even numbers
    print(i)
# Output: 1 3

Nested Loops โ€” Patterns

# Print a triangle pattern
for i in range(1, 5):
    for j in range(i):
        print("*", end="")
    print()
# Output:
# *
# **
# ***
# ****
โœ๏ธ Practice: Write a program using a for loop to print the multiplication table (1 to 10) of any number entered by the user.
Unit 7

Strings & String Methods

Working with text data in Python.

What is a String?

A string is a sequence of characters enclosed in single (' '), double (" "), or triple (''' ''') quotes. Strings in Python are immutable โ€” once created, individual characters cannot be changed directly.

s1 = 'Hello'
s2 = "World"
s3 = '''This is a
multi-line string'''

Indexing & Slicing

Each character has a position (index) starting from 0. Negative indexes count from the end.

word = "Python"
print(word[0])      # P (first character)
print(word[-1])     # n (last character)
print(word[0:4])    # Pyth (index 0 to 3)
print(word[2:])     # thon (index 2 to end)
print(word[::-1])   # nohtyP (reversed string)

Common String Methods

MethodDescriptionExample
upper()Converts to uppercase"hi".upper() โ†’ "HI"
lower()Converts to lowercase"HI".lower() โ†’ "hi"
strip()Removes leading/trailing spaces" hi ".strip() โ†’ "hi"
replace()Replaces text"hi".replace("h","H") โ†’ "Hi"
split()Splits into a list"a,b".split(",") โ†’ ['a','b']
join()Joins a list into a string"-".join(['a','b']) โ†’ "a-b"
find()Returns index of substring"hello".find("l") โ†’ 2
len()Returns lengthlen("hello") โ†’ 5

String Concatenation & Repetition

first = "Pak"
last = "Notes"
print(first + last)      # PakNotes  (concatenation)
print(first * 3)          # PakPakPak (repetition)
โœ๏ธ Practice: Take a sentence as input and print: the total number of characters, the sentence in uppercase, and the sentence reversed.
Unit 8

Lists & Tuples

Storing collections of ordered data.

What is a List?

A list is an ordered, mutable collection that can hold items of different data types, defined using square brackets [ ].

fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, True]
print(fruits[0])        # apple
fruits.append("mango")  # add an item
fruits[1] = "grapes"    # update an item
print(fruits)

Common List Methods

MethodDescription
append(x)Adds item x at the end
insert(i, x)Inserts x at index i
remove(x)Removes first occurrence of x
pop(i)Removes & returns item at index i
sort()Sorts the list in ascending order
reverse()Reverses the list
len(list)Returns number of items

List Slicing

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])     # [20, 30, 40]
print(numbers[:3])      # [10, 20, 30]
print(numbers[::2])     # [10, 30, 50] (every 2nd item)

List Comprehension (Introduction)

A compact, one-line way to create a new list by transforming or filtering an existing one.

squares = [x**2 for x in range(1, 6)]
print(squares)             # [1, 4, 9, 16, 25]

evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)                # [2, 4, 6, 8, 10]

What is a Tuple?

A tuple is like a list but immutable โ€” once created, its values cannot change. Tuples use parentheses ( ).

point = (10, 20)
print(point[0])      # 10
# point[0] = 5       # Error! Tuples cannot be modified

List vs Tuple

FeatureListTuple
Syntax[1, 2, 3](1, 2, 3)
MutableYesNo
SpeedSlowerFaster
Use CaseData that changesFixed data (e.g. coordinates)

Packing & Unpacking

point = (10, 20)
x, y = point          # unpacking
print(x, y)             # 10 20

a, b, c = 1, 2, 3      # packing into separate variables
โœ๏ธ Practice: Create a list of 5 students' marks. Find and print the highest, lowest, and average using max(), min(), and sum().
Unit 9

Dictionaries & Sets

Key-value pairs and collections of unique items.

What is a Dictionary?

A dictionary stores data as key-value pairs. Each key must be unique, and values can be of any data type. Dictionaries use curly braces { }.

student = {"name": "Ali", "age": 20, "gpa": 3.7}
print(student["name"])       # Ali
student["age"] = 21            # update value
student["dept"] = "CS"         # add new key

Common Dictionary Methods

MethodDescription
keys()Returns all keys
values()Returns all values
items()Returns key-value pairs
get(key)Safely returns value (no error if missing)
pop(key)Removes a key and returns its value
update()Adds/updates multiple key-value pairs

Iterating Over a Dictionary

student = {"name": "Ali", "age": 20, "gpa": 3.7}
for key, value in student.items():
    print(key, "->", value)

What is a Set?

A set is an unordered collection of unique items โ€” duplicates are automatically removed. Sets use curly braces { } without key-value pairs.

nums = {1, 2, 2, 3, 3, 3}
print(nums)             # {1, 2, 3} โ€” duplicates removed
nums.add(4)
nums.remove(1)

Set Operations

OperationSymbolExample
Union|a | b
Intersection&a & b
Difference-a - b
Symmetric Difference^a ^ b
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b)    # {1, 2, 3, 4}  union
print(a & b)    # {2, 3}        intersection
print(a - b)    # {1}           difference
๐Ÿ’ก Dictionaries are perfect for storing structured records (like a student profile), while sets are perfect for removing duplicates and fast membership checks.
โœ๏ธ Practice: Create a dictionary to store a student's record (name, roll number, three subject marks). Calculate and print the total and percentage.
Unit 10

Functions & Scope

Writing reusable, organized blocks of code.

What is a Function?

A function is a reusable block of code that performs a specific task. Functions are defined using the def keyword and help avoid repeating code.

def greet(name):
    print(f"Hello, {name}!")

greet("Sara")         # Hello, Sara!
greet("Ahmed")         # Hello, Ahmed!

Parameters & Arguments

TypeDescriptionExample
PositionalPassed in ordergreet("Ali")
DefaultHas a fallback valuedef greet(name="Guest")
KeywordPassed by parameter namegreet(name="Ali")
def add(a, b=10):              # b has a default value
    return a + b

print(add(5))            # 15 (uses default b=10)
print(add(5, 20))        # 25
print(add(a=5, b=2))     # 7 (keyword arguments)

*args and **kwargs

Used when the number of arguments isn't fixed. *args collects extra positional arguments into a tuple, **kwargs collects extra keyword arguments into a dictionary.

def total(*args):
    return sum(args)
print(total(1, 2, 3, 4))     # 10

def show_info(**kwargs):
    for key, value in kwargs.items():
        print(key, ":", value)
show_info(name="Ali", age=20)

The return Statement

return sends a value back to wherever the function was called, and immediately ends the function.

def square(n):
    return n * n

result = square(5)
print(result)     # 25

Local vs Global Scope

ScopeDescription
LocalVariable created inside a function โ€” only accessible there
GlobalVariable created outside any function โ€” accessible everywhere
x = 10            # global variable
def show():
    x = 5           # local variable (different from global x)
    print("Inside:", x)
show()               # Inside: 5
print("Outside:", x) # Outside: 10

Recursion

A recursive function calls itself to solve a smaller version of the same problem.

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

print(factorial(5))    # 120
โœ๏ธ Practice: Write a function is_prime(n) that returns True if a number is prime, otherwise False. Test it for numbers 1 to 20.
Unit 11

Lambda, Map, Filter & Comprehensions

Writing short, powerful, functional-style code.

Lambda Functions

A lambda function is a small, anonymous (unnamed) function written in a single line โ€” useful for short operations.

square = lambda x: x * x
print(square(5))         # 25

add = lambda a, b: a + b
print(add(3, 4))          # 7

The map() Function

map() applies a function to every item in a sequence and returns a new sequence of results.

numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares)           # [1, 4, 9, 16]

The filter() Function

filter() keeps only the items for which a function returns True.

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)             # [2, 4, 6]

The reduce() Function

reduce() (from the functools module) repeatedly applies a function to reduce a sequence to a single value.

from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda a, b: a * b, numbers)
print(product)            # 24

Comprehensions โ€” List, Dict & Set

TypeSyntaxExample
List[expr for x in seq][x*2 for x in range(5)]
Dict{k:v for x in seq}{x: x*2 for x in range(3)}
Set{expr for x in seq}{x%3 for x in range(10)}
squares_dict = {x: x**2 for x in range(1, 5)}
print(squares_dict)    # {1: 1, 2: 4, 3: 9, 4: 16}
โœ๏ธ Practice: Use map() and a lambda function to convert a list of temperatures from Celsius to Fahrenheit (F = C * 9/5 + 32).
Unit 12

Exception Handling

Catching and managing errors gracefully.

What is an Exception?

An exception is an error that occurs during program execution and stops the program unless it is handled. Python uses try-except blocks to catch and manage these errors gracefully.

print(10 / 0)
# Output: ZeroDivisionError: division by zero

try-except Block

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print(result)
except ZeroDivisionError:
    print("You cannot divide by zero!")
except ValueError:
    print("Please enter a valid number!")

Common Built-in Exceptions

ExceptionOccurs When
ZeroDivisionErrorDividing a number by zero
ValueErrorInvalid value for an operation, e.g. int("abc")
TypeErrorOperation on incompatible types
IndexErrorList index out of range
KeyErrorDictionary key not found
FileNotFoundErrorFile does not exist

else and finally

else runs only if no exception occurred, and finally always runs โ€” whether an exception occurred or not (useful for cleanup).

try:
    x = int("10")
except ValueError:
    print("Invalid input")
else:
    print("No errors:", x)
finally:
    print("Execution finished")

Raising Exceptions โ€” raise

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

set_age(-5)    # raises ValueError

Custom Exceptions

class InsufficientBalanceError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientBalanceError("Not enough balance!")
    return balance - amount
โœ๏ธ Practice: Write a program that asks the user for two numbers and divides them. Handle ZeroDivisionError and ValueError using try-except, and print "Done" in the finally block.
Unit 13

File Handling

Reading from and writing to files on disk.

Opening a File โ€” open()

Python's open() function is used to work with files. It takes a filename and a mode that specifies the operation to perform.

file = open("notes.txt", "r")     # open for reading
content = file.read()
file.close()                        # always close the file

File Modes

ModeMeaning
"r"Read (default) โ€” file must exist
"w"Write โ€” creates new file or overwrites existing
"a"Append โ€” adds data at the end of the file
"r+"Read and write
"x"Create a new file โ€” fails if it already exists

Reading from a File

MethodDescription
read()Reads the entire file as one string
readline()Reads a single line
readlines()Reads all lines into a list
with open("notes.txt", "r") as file:
    for line in file:
        print(line.strip())

Writing to a File

with open("notes.txt", "w") as file:
    file.write("Pak Notes Hub\n")
    file.write("Python Programming Course\n")

with open("notes.txt", "a") as file:
    file.write("Added later using append mode\n")

The with Statement

Using with open(...) as file: automatically closes the file when the block ends โ€” even if an error occurs. This is the recommended way to work with files.

๐Ÿ’ก Without with, you must manually call file.close() โ€” forgetting it can cause data loss or memory issues. Always prefer the with statement.
โœ๏ธ Practice: Write a program that asks for 5 student names and writes them to a file students.txt, one name per line. Then read and display the file's contents.
Unit 14

Object-Oriented Programming (OOP)

Classes, objects, and the four pillars of OOP.

What is OOP? โ€” The Four Pillars

Encapsulation
Bundling data & methods together
Inheritance
Reusing code from a parent class
Polymorphism
Same method, different behavior
Abstraction
Hiding complex implementation details

Classes & Objects

A class is a blueprint for creating objects. An object is an instance of a class with its own data.

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

    def display(self):
        print(f"{self.roll_no} - {self.name}")

s1 = Student("Ali", 101)
s1.display()           # 101 - Ali

__init__ Constructor & self

__init__ is a special method automatically called when an object is created โ€” it initializes the object's attributes. self refers to the current object instance.

Instance vs Class Variables

TypeDescriptionExample
Instance VariableBelongs to one specific objectself.name
Class VariableShared by all objects of the classStudent.school_name

Inheritance

Inheritance allows a child class to reuse the attributes and methods of a parent class.

class Person:
    def __init__(self, name):
        self.name = name
    def show(self):
        print("Name:", self.name)

class Student(Person):            # Student inherits from Person
    def __init__(self, name, roll_no):
        super().__init__(name)     # call parent constructor
        self.roll_no = roll_no

s = Student("Sara", 12)
s.show()                # Name: Sara

Polymorphism

Polymorphism means the same method name behaves differently for different classes.

class Cat:
    def sound(self):
        print("Meow")

class Dog:
    def sound(self):
        print("Woof")

for animal in [Cat(), Dog()]:
    animal.sound()        # Meow, then Woof

Encapsulation

Encapsulation restricts direct access to an object's data using private (double underscore __) or protected (single underscore _) attributes.

class Account:
    def __init__(self, balance):
        self.__balance = balance      # private attribute

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

Dunder (Magic) Methods

MethodPurpose
__init__Object constructor
__str__Defines what print(object) displays
__len__Defines behavior of len(object)
__add__Defines behavior of the + operator
โœ๏ธ Practice: Create a class Book with attributes title, author, and price. Add a method discount() that reduces the price by 10%. Create two Book objects and display their details.
Unit 15

Modules, Packages & Final Project

Organizing code and building a real mini-project.

What is a Module?

A module is simply a Python file (.py) containing functions, classes, or variables that can be reused in other programs using import.

import math
print(math.sqrt(25))      # 5.0
print(math.pi)              # 3.141592653589793

from random import randint
print(randint(1, 10))      # random number between 1 and 10

Useful Standard Library Modules

ModulePurpose
mathMathematical functions (sqrt, pow, pi)
randomGenerate random numbers
datetimeWork with dates and times
osInteract with the operating system
sysSystem-specific parameters & functions
timeTime-related functions, delays

Creating Your Own Module

Save any Python file (e.g. mymath.py) and import it into another file in the same folder using import mymath.

# mymath.py
def add(a, b):
    return a + b

# main.py
import mymath
print(mymath.add(3, 4))     # 7

Packages & pip

A package is a folder containing multiple related modules. Python's package manager, pip, installs third-party packages from PyPI (Python Package Index).

pip install numpy
pip install pandas
pip list                     # shows installed packages

Final Project โ€” Console-Based To-Do List

Let's combine everything learned โ€” functions, loops, lists, dictionaries, and exception handling โ€” into one mini project.

tasks = []

def show_menu():
    print("\n--- TO-DO LIST ---")
    print("1. Add Task")
    print("2. View Tasks")
    print("3. Remove Task")
    print("4. Exit")

def add_task():
    task = input("Enter task: ")
    tasks.append(task)
    print("Task added!")

def view_tasks():
    if not tasks:
        print("No tasks yet.")
    for i, task in enumerate(tasks, start=1):
        print(f"{i}. {task}")

def remove_task():
    view_tasks()
    try:
        num = int(input("Enter task number to remove: "))
        tasks.pop(num - 1)
        print("Task removed!")
    except (ValueError, IndexError):
        print("Invalid task number.")

while True:
    show_menu()
    choice = input("Choose an option: ")
    if choice == "1":
        add_task()
    elif choice == "2":
        view_tasks()
    elif choice == "3":
        remove_task()
    elif choice == "4":
        print("Goodbye!")
        break
    else:
        print("Invalid choice, try again.")

๐Ÿ Python Quick Reference โ€” Syntax Cheat Sheet

ConceptSyntax
Variablex = 10
If statementif x > 5:
For loopfor i in range(5):
While loopwhile x > 0:
Functiondef func(x):
Classclass Name:
List[1, 2, 3]
Dictionary{"key": "value"}
Importimport module
Try-Excepttry: ... except Error:
File Readwith open("f.txt") as f:
Lambdalambda x: x*2
โœ๏ธ Practice: Extend the To-Do List project by adding a feature to save tasks to a file (tasks.txt) and load them back when the program starts, using file handling.

๐ŸŽ‰ Congratulations!

You have completed the Python Programming Course by Pak Notes Hub!

You now know Variables, Data Types, Control Flow, Functions, Data Structures, OOP, File & Exception Handling โ€” and even built a real mini-project. Best of luck in your exams and coding journey! ๐ŸŒŸ

๐Ÿ“Š Course Summary

#UnitKey Concept
1Introduction to PythonHistory, Features, First Program
2Variables & Data Typesint, float, str, bool, type casting
3Operators & ExpressionsArithmetic, Logical, Comparison
4Input, Output & Formattingprint(), input(), f-strings
5Decision Makingif, elif, else, ternary operator
6Loopsfor, while, break, continue
7StringsIndexing, slicing, string methods
8Lists & TuplesMutable vs immutable sequences
9Dictionaries & SetsKey-value pairs, unique collections
10Functions & Scopedef, *args, **kwargs, recursion
11Lambda & Comprehensionsmap, filter, reduce, comprehensions
12Exception Handlingtry, except, else, finally, raise
13File Handlingopen(), read/write, with statement
14OOP in PythonClasses, Inheritance, Polymorphism
15Modules & Final Projectimport, pip, To-Do List project

www.paknoteshub.online  ยท  More courses coming soon!