Loading...
Loading...
Python is an interpreted, high-level, general-purpose programming language created by Guido van Rossum in 1991.
Key Features:
# Numbers
x = 10 # int
y = 3.14 # float
z = 2 + 3j # complex
# String
s = "WohoTech"
s[0] # 'W' — indexing
s[1:4] # 'oho' — slicing
s[::-1] # 'hceTohol' — reverse
f"Hello {s}" # f-string formatting
# List (mutable, ordered)
lst = [1, 2, 3, 4, 5]
lst.append(6)
lst.sort()
lst.reverse()
# Tuple (immutable, ordered)
t = (1, 2, 3)
t[0] # 1
# t[0] = 5 # TypeError!
# Dictionary (key-value pairs)
d = {'name': 'Rahul', 'age': 20}
d['cgpa'] = 8.5 # Add
del d['age'] # Delete
d.get('name', 'N/A') # Safe access
# Set (unique, unordered)
s = {1, 2, 3, 2, 1} # {1, 2, 3}
s.add(4)
s.union({5, 6})
s.intersection({2, 3, 7})
class Animal:
species = "Animal" # Class variable
def __init__(self, name, sound):
self.name = name # Instance variable
self.sound = sound
def speak(self):
return f"{self.name} says {self.sound}"
def __str__(self): # String representation
return f"Animal({self.name})"
def __repr__(self): # Developer representation
return f"Animal(name='{self.name}')"
class Dog(Animal): # Inheritance
def __init__(self, name):
super().__init__(name, "Woof") # Call parent init
def fetch(self, item):
return f"{self.name} fetches {item}!"
def speak(self): # Method overriding
return super().speak() + " (loud)"
dog = Dog("Tommy")
print(dog.speak()) # Tommy says Woof (loud)
print(isinstance(dog, Animal)) # True
print(issubclass(Dog, Animal)) # True
Magic Methods (Dunder):
| Method | Triggered by |
|---|---|
| __init__ | Object creation |
| __str__ | str(obj), print(obj) |
| __len__ | len(obj) |
| __add__ | obj1 + obj2 |
| __eq__ | obj1 == obj2 |
| __lt__ | obj1 < obj2 |
| __iter__ | for loop, iter() |
# Writing
with open("data.txt", "w") as f:
f.write("Hello WohoTech\n")
f.writelines(["Line 1\n", "Line 2\n"])
# Reading
with open("data.txt", "r") as f:
content = f.read() # Read all
lines = f.readlines() # List of lines
for line in open("data.txt"): # Iterate lines
print(line.strip())
# JSON
import json
data = {"name": "WohoTech", "users": 1000}
with open("config.json", "w") as f:
json.dump(data, f, indent=2)
with open("config.json") as f:
loaded = json.load(f)
try:
x = int(input("Enter number: "))
result = 100 / x
except ValueError as e:
print(f"Invalid input: {e}")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print(f"Result: {result}") # Runs if no exception
finally:
print("Always runs — cleanup here")
# Custom exception
class InsufficientFundsError(Exception):
def __init__(self, amount, balance):
super().__init__(f"Need {amount}, have {balance}")
self.amount = amount
self.balance = balance
raise InsufficientFundsError(500, 200)
import time
import functools
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end-start:.4f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "done"
slow_function() # slow_function took 1.0001s
# Class decorator
def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class Config:
def __init__(self):
self.debug = True
# Generator function (lazy evaluation)
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a # Suspends and returns value
a, b = b, a + b
for num in fibonacci(10):
print(num)
# Generator expression (like list comprehension but lazy)
squares = (x**2 for x in range(100)) # Doesn't compute yet
next(squares) # 0 — compute one at a time
# Custom iterator
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
self.current += 1
return self.current - 1
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
# Dict comprehension
word_len = {word: len(word) for word in ["python", "java", "c++"]}
# Set comprehension
unique_lengths = {len(word) for word in ["hello", "world", "hi"]}
# Nested comprehension
matrix = [[i*j for j in range(1,4)] for i in range(1,4)]
from functools import reduce
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# map — apply function to each element
doubled = list(map(lambda x: x*2, nums))
# filter — keep elements satisfying condition
evens = list(filter(lambda x: x % 2 == 0, nums))
# reduce — reduce to single value
total = reduce(lambda x, y: x + y, nums) # 55
# sorted with key
students = [("Alice", 8.5), ("Bob", 9.0), ("Charlie", 7.8)]
sorted_students = sorted(students, key=lambda s: s[1], reverse=True)
Q1 (2023): Explain the difference between @staticmethod and @classmethod.
class Example:
count = 0
@classmethod
def get_count(cls): # First arg is class itself
return cls.count # Can access class variables
@staticmethod
def validate(value): # No cls or self
return value > 0 # Cannot access class/instance
Q2 (2022): Write a generator to yield prime numbers up to n.
def primes_up_to(n):
def is_prime(num):
if num < 2: return False
for i in range(2, int(num**0.5)+1):
if num % i == 0: return False
return True
for i in range(2, n+1):
if is_prime(i):
yield i
Q3 (2024): What is multiple inheritance and MRO in Python?
Python uses C3 linearization (MRO) to determine method lookup order in multiple inheritance. Use ClassName.__mro__ to see order. Diamond problem solved by MRO.
Complete Python notes for MCA — OOP in Python, file handling, exceptions, decorators, generators, Django basics, and data structures in Python with examples.
56 pages · 2.8 MB · Updated 2026-03-11
Python is interpreted, dynamically typed, and garbage collected. No memory management needed. Indentation instead of braces. Rich standard library. Much faster development time.
Global Interpreter Lock (GIL) allows only one thread to execute Python bytecode at a time. This means CPU-bound multithreaded Python code doesn't truly parallelize. Use multiprocessing for CPU tasks.
Python Programming for MCA — Complete Notes with Programs
Python Programming
Data Structures and Algorithms for MCA — Complete Notes
Data Structures and Algorithms
Advanced Machine Learning & Deep Learning — MTech/MCA Complete Notes
Machine Learning
DBMS Complete Notes — B.Tech CS Sem 4
Database Management Systems
Compiler Design — Complete Notes CS Sem 6
Compiler Design
Your feedback helps us improve notes and tutorials.