Python Programming
Complete Notes
Variables to OOP ยท Data Structures ยท File & Exception Handling โ All in Easy English
๐ Table of Contents โ 15 Units
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.
Key Features of Python
Compiled vs Interpreted Languages
| Feature | Compiled (C, C++) | Interpreted (Python) |
|---|---|---|
| Execution | Converted to machine code before running | Executed line-by-line by an interpreter |
| Speed | Generally faster | Generally slower |
| Errors | Shown only after full compilation | Shown immediately, line by line |
| Portability | Needs recompiling per OS | Same 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.
| Category | Examples |
|---|---|
| Values | True, False, None |
| Logical | and, or, not, in, is |
| Control Flow | if, elif, else, for, while, break, continue, pass |
| Functions / Classes | def, return, class, lambda |
| Modules | import, from, as |
| Error Handling | try, except, finally, raise, with |
python --version in the terminal, and write a program that prints your name, roll number, and university on three separate lines.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 โ
ageandAgeare different variables - Cannot be a Python keyword (e.g.
class,for,if) - Should be descriptive โ
student_nameis better thanx
Python Data Types
| Data Type | Example | Description |
|---|---|---|
| int | 10, -5, 2024 | Whole numbers (no decimal point) |
| float | 3.14, -0.5 | Numbers with a decimal point |
| str | "Hello" | Sequence of characters (text) |
| bool | True, False | Logical 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 |
| NoneType | None | Represents "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).
| Function | Converts To | Example |
|---|---|---|
| int() | Integer | int("10") โ 10 |
| float() | Float | float("3.5") โ 3.5 |
| str() | String | str(25) โ "25" |
| bool() | Boolean | bool(1) โ True |
| list() | List | list("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: 99Mutable vs Immutable Types
| Mutable (can be changed) | Immutable (cannot be changed) |
|---|---|
| list | int, float, bool |
| dict | str |
| set | tuple |
type().Operators & Expressions
Arithmetic, comparison, logical and other operators.
Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 2 | 7 |
| - | Subtraction | 5 - 2 | 3 |
| * | Multiplication | 5 * 2 | 10 |
| / | Division (float) | 5 / 2 | 2.5 |
| // | Floor Division | 5 // 2 | 2 |
| % | Modulus (remainder) | 5 % 2 | 1 |
| ** | Exponent (power) | 5 ** 2 | 25 |
Comparison (Relational) Operators
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to | 5 == 5 โ True |
| != | Not equal to | 5 != 3 โ True |
| > | Greater than | 5 > 3 โ True |
| < | Less than | 5 < 3 โ False |
| >= | Greater or equal | 5 >= 5 โ True |
| <= | Less or equal | 5 <= 4 โ False |
Logical Operators
| Operator | Meaning | Example |
|---|---|---|
| and | True if both conditions are True | (5>2) and (3>1) โ True |
| or | True if at least one condition is True | (5>2) or (1>3) โ True |
| not | Reverses the result | not(5>2) โ False |
Assignment Operators
| Operator | Example | Same As |
|---|---|---|
| = | x = 5 | x = 5 |
| += | x += 3 | x = x + 3 |
| -= | x -= 3 | x = x - 3 |
| *= | x *= 3 | x = x * 3 |
| //= | x //= 3 | x = x // 3 |
Membership & Identity Operators
| Operator | Use | Example |
|---|---|---|
| in | Checks if a value exists in a sequence | "a" in "cat" โ True |
| not in | Checks if a value does not exist | 5 not in [1,2,3] โ True |
| is | Checks if two variables point to the same object | a is b |
| is not | Checks they do not point to the same object | a 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
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
| Method | Example | Output |
|---|---|---|
| f-string | f"My name is {name}" | My name is Ali |
| .format() | "My name is {}".format(name) | My name is Ali |
| % operator | "My name is %s" % name | My name is Ali |
name = "Ayesha"
gpa = 3.85
print(f"Student: {name}, GPA: {gpa:.1f}")
# Output: Student: Ayesha, GPA: 3.9.format() or % formatting.Escape Sequences
| Escape Sequence | Meaning |
|---|---|
| \n | New line |
| \t | Tab space |
| \\ | Backslash |
| \' | Single quote |
| \" | Double quote |
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
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
| Syntax | Meaning | Example |
|---|---|---|
| range(stop) | 0 to stop-1 | range(5) โ 0,1,2,3,4 |
| range(start, stop) | start to stop-1 | range(2,6) โ 2,3,4,5 |
| range(start, stop, step) | with custom step | range(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 += 1break, continue & pass
| Keyword | Purpose |
|---|---|
| break | Immediately exits the loop |
| continue | Skips current iteration, moves to next |
| pass | Does 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 3Nested Loops โ Patterns
# Print a triangle pattern
for i in range(1, 5):
for j in range(i):
print("*", end="")
print()
# Output:
# *
# **
# ***
# ****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
| Method | Description | Example |
|---|---|---|
| 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 length | len("hello") โ 5 |
String Concatenation & Repetition
first = "Pak" last = "Notes" print(first + last) # PakNotes (concatenation) print(first * 3) # PakPakPak (repetition)
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
| Method | Description |
|---|---|
| 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
| Feature | List | Tuple |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutable | Yes | No |
| Speed | Slower | Faster |
| Use Case | Data that changes | Fixed 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
max(), min(), and sum().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 keyCommon Dictionary Methods
| Method | Description |
|---|---|
| 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
| Operation | Symbol | Example |
|---|---|---|
| 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} differenceFunctions & 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
| Type | Description | Example |
|---|---|---|
| Positional | Passed in order | greet("Ali") |
| Default | Has a fallback value | def greet(name="Guest") |
| Keyword | Passed by parameter name | greet(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) # 25Local vs Global Scope
| Scope | Description |
|---|---|
| Local | Variable created inside a function โ only accessible there |
| Global | Variable 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: 10Recursion
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)) # 120is_prime(n) that returns True if a number is prime, otherwise False. Test it for numbers 1 to 20.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
| Type | Syntax | Example |
|---|---|---|
| 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}map() and a lambda function to convert a list of temperatures from Celsius to Fahrenheit (F = C * 9/5 + 32).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
| Exception | Occurs When |
|---|---|
| ZeroDivisionError | Dividing a number by zero |
| ValueError | Invalid value for an operation, e.g. int("abc") |
| TypeError | Operation on incompatible types |
| IndexError | List index out of range |
| KeyError | Dictionary key not found |
| FileNotFoundError | File 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 ValueErrorCustom Exceptions
class InsufficientBalanceError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError("Not enough balance!")
return balance - amountFile 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 fileFile Modes
| Mode | Meaning |
|---|---|
| "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
| Method | Description |
|---|---|
| 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.
with, you must manually call file.close() โ forgetting it can cause data loss or memory issues. Always prefer the with statement.students.txt, one name per line. Then read and display the file's contents.Object-Oriented Programming (OOP)
Classes, objects, and the four pillars of OOP.
What is OOP? โ The Four Pillars
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
| Type | Description | Example |
|---|---|---|
| Instance Variable | Belongs to one specific object | self.name |
| Class Variable | Shared by all objects of the class | Student.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: SaraPolymorphism
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 WoofEncapsulation
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.__balanceDunder (Magic) Methods
| Method | Purpose |
|---|---|
| __init__ | Object constructor |
| __str__ | Defines what print(object) displays |
| __len__ | Defines behavior of len(object) |
| __add__ | Defines behavior of the + operator |
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.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
| Module | Purpose |
|---|---|
| math | Mathematical functions (sqrt, pow, pi) |
| random | Generate random numbers |
| datetime | Work with dates and times |
| os | Interact with the operating system |
| sys | System-specific parameters & functions |
| time | Time-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)) # 7Packages & 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
| Concept | Syntax |
|---|---|
| Variable | x = 10 |
| If statement | if x > 5: |
| For loop | for i in range(5): |
| While loop | while x > 0: |
| Function | def func(x): |
| Class | class Name: |
| List | [1, 2, 3] |
| Dictionary | {"key": "value"} |
| Import | import module |
| Try-Except | try: ... except Error: |
| File Read | with open("f.txt") as f: |
| Lambda | lambda x: x*2 |
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
| # | Unit | Key Concept |
|---|---|---|
| 1 | Introduction to Python | History, Features, First Program |
| 2 | Variables & Data Types | int, float, str, bool, type casting |
| 3 | Operators & Expressions | Arithmetic, Logical, Comparison |
| 4 | Input, Output & Formatting | print(), input(), f-strings |
| 5 | Decision Making | if, elif, else, ternary operator |
| 6 | Loops | for, while, break, continue |
| 7 | Strings | Indexing, slicing, string methods |
| 8 | Lists & Tuples | Mutable vs immutable sequences |
| 9 | Dictionaries & Sets | Key-value pairs, unique collections |
| 10 | Functions & Scope | def, *args, **kwargs, recursion |
| 11 | Lambda & Comprehensions | map, filter, reduce, comprehensions |
| 12 | Exception Handling | try, except, else, finally, raise |
| 13 | File Handling | open(), read/write, with statement |
| 14 | OOP in Python | Classes, Inheritance, Polymorphism |
| 15 | Modules & Final Project | import, pip, To-Do List project |
www.paknoteshub.online ยท More courses coming soon!

