Loading...
Loading...
Python is a high-level, interpreted, dynamically-typed programming language created by Guido van Rossum in 1991.
Key Features:
# No type declaration needed
name = "WohoTech" # str
age = 20 # int
cgpa = 8.5 # float
is_student = True # bool
# Type checking
print(type(name)) # <class 'str'>
# Type conversion
x = int("42") # str → int
y = str(3.14) # float → str
z = float(10) # int → float
s = "Hello, World!"
# Slicing
print(s[0:5]) # Hello
print(s[-6:-1]) # World
print(s[::-1]) # !dlroW ,olleH (reverse)
# Methods
print(s.upper()) # HELLO, WORLD!
print(s.lower()) # hello, world!
print(s.replace("Hello", "Hi")) # Hi, World!
print(s.split(", ")) # ['Hello', 'World!']
print(s.strip()) # removes whitespace
# f-strings (modern)
name = "Rahul"
print(f"My name is {name} and I am {age} years old.")
fruits = ["apple", "banana", "cherry"]
# Operations
fruits.append("mango") # add to end
fruits.insert(1, "grape") # insert at index
fruits.remove("banana") # remove by value
popped = fruits.pop() # remove and return last
fruits.sort() # sort in place
fruits.reverse() # reverse in place
# List comprehension (Pythonic!)
squares = [x**2 for x in range(1, 11)]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
evens = [x for x in range(20) if x % 2 == 0]
# Tuple — immutable
point = (3, 4)
x, y = point # tuple unpacking
# Set — unique elements
s = {1, 2, 3, 2, 1}
print(s) # {1, 2, 3}
s.add(4)
s1 & s2 # intersection
s1 | s2 # union
s1 - s2 # difference
# Dictionary
student = {"name": "Rahul", "cgpa": 8.5, "branch": "MCA"}
student["semester"] = 1 # add
del student["semester"] # delete
print(student.get("name", "N/A")) # safe access
for k, v in student.items(): # iterate
print(f"{k}: {v}")
# Basic function
def greet(name, greeting="Hello"): # default parameter
return f"{greeting}, {name}!"
print(greet("Rahul")) # Hello, Rahul!
print(greet("Priya", "Hi")) # Hi, Priya!
# *args — variable positional arguments
def add(*numbers):
return sum(numbers)
print(add(1, 2, 3, 4)) # 10
# **kwargs — variable keyword arguments
def info(**details):
for key, val in details.items():
print(f"{key}: {val}")
info(name="Rahul", age=22, city="Delhi")
# Lambda (anonymous function)
square = lambda x: x**2
print(square(5)) # 25
# Map, Filter, Reduce
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x%2==0, nums))
def timer_decorator(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time()-start:.4f}s")
return result
return wrapper
@timer_decorator
def slow_function():
import time; time.sleep(1)
class BankAccount:
bank_name = "WohoBank" # class variable (shared)
def __init__(self, owner, balance=0): # constructor
self.owner = owner # instance variable
self.__balance = balance # private (name mangling)
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return True
return False
@property
def balance(self): # getter
return self.__balance
def __str__(self): # string representation
return f"Account({self.owner}, Balance: {self.__balance})"
@classmethod
def get_bank_name(cls):
return cls.bank_name
@staticmethod
def is_valid_amount(amount):
return amount > 0
# Inheritance
class SavingsAccount(BankAccount):
def __init__(self, owner, balance, interest_rate):
super().__init__(owner, balance)
self.interest_rate = interest_rate
def add_interest(self):
interest = self.balance * self.interest_rate
self.deposit(interest)
# Writing to file
with open("data.txt", "w") as f: # 'w'=write, 'a'=append, 'r'=read
f.write("Hello, File!\n")
f.writelines(["Line 1\n", "Line 2\n"])
# Reading from file
with open("data.txt", "r") as f:
content = f.read() # entire file
# OR
lines = f.readlines() # list of lines
# OR
for line in f: # line by line (memory efficient)
print(line.strip())
# JSON
import json
data = {"name": "Rahul", "cgpa": 8.5}
with open("student.json", "w") as f:
json.dump(data, f, indent=2)
with open("student.json", "r") as f:
loaded = json.load(f)
try:
x = int(input("Enter number: "))
result = 100 / x
print(f"Result: {result}")
except ValueError:
print("Invalid input — please enter a number")
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print("No errors occurred!") # runs if no exception
finally:
print("This always runs") # cleanup code
# Custom exception
class InsufficientFundsError(Exception):
def __init__(self, amount, balance):
self.message = f"Cannot withdraw {amount}. Balance: {balance}"
super().__init__(self.message)
Q1 (2023): What is the difference between deepcopy and shallow copy?
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original) # copies container, not nested objects
deep = copy.deepcopy(original) # copies everything recursively
original[0][0] = 99
print(shallow[0][0]) # 99 — shares nested objects!
print(deep[0][0]) # 1 — completely independent
Q2 (2023): Write a Python program using generators to yield squares of 1 to n.
def squares(n):
for i in range(1, n+1):
yield i**2
for sq in squares(5):
print(sq) # 1, 4, 9, 16, 25
Q3 (2022): What is list comprehension? Give example. List comprehension is a concise way to create lists in Python using a single line.
# Traditional
result = []
for x in range(10):
if x % 2 == 0:
result.append(x**2)
# List comprehension
result = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]
Complete Python programming notes for MCA Semester 1 — basics, OOP, file handling, exception handling, data structures with programs and solved PYQs.
48 pages · 2.4 MB · Updated 2026-03-11
Yes! Python is used in web development (Django), data science (pandas, numpy), AI/ML, automation, and more. It is the most in-demand language for non-systems programming jobs.
List: ordered, mutable, allows duplicates []. Tuple: ordered, immutable, allows duplicates (). Set: unordered, mutable, no duplicates {}. Dictionary: key-value pairs, keys unique {}.
A decorator is a function that takes another function as argument and extends its behavior without modifying it. Uses @ syntax. Common: @staticmethod, @classmethod, @property.
Data Structures and Algorithms for MCA — Complete Notes
Data Structures and Algorithms
Python Advanced Programming — Complete MCA Notes
Python Programming
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.