Learn real Python power now — Functions, OOP, Data Structures, and more!
A function is a reusable code block — write once, use multiple times!
# Basic function
def greet(name):
"""This function prints a greeting"""
print(f"Hello, {name}! Welcome! 🎉")
greet("Himanshu") # Hello, Himanshu! Welcome! 🎉
greet("Python") # Hello, Python! Welcome! 🎉
# Return value
def add(a, b):
return a + b
result = add(10, 20)
print(f"Sum: {result}") # Sum: 30
# Default parameters
def power(base, exp=2):
return base ** exp
print(power(5)) # 25 (default exp=2)
print(power(2, 10)) # 1024
# *args — Multiple arguments
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4, 5)) # 15
# **kwargs — Keyword arguments
def profile(**info):
for key, value in info.items():
print(f"{key}: {value}")
profile(name="Himanshu", age=20, city="Delhi")
# Lambda function — One-liner function
square = lambda x: x ** 2
print(square(5)) # 25
# Scope — Local vs Global
x = 100 # Global
def demo():
x = 50 # Local — only inside function
print(f"Inside: {x}") # 50
demo()
print(f"Outside: {x}") # 100
Q1. Create a function to calculate factorial. Medium
def factorial(n):
if n <= 1: return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
Q2. Create a function to check if a number is prime or not. Medium
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
for num in range(1, 20):
if is_prime(num): print(num, end=" ")
# 2 3 5 7 11 13 17 19
A List is an ordered, mutable collection — store multiple items in one place!
# Creating lists
fruits = ["Apple", "Banana", "Mango", "Orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "Hello", 3.14, True]
# Accessing elements
print(fruits[0]) # Apple
print(fruits[-1]) # Orange
print(fruits[1:3]) # ['Banana', 'Mango']
# List methods
fruits.append("Grapes") # Add at end
fruits.insert(1, "Kiwi") # Add at index
fruits.remove("Banana") # Remove by value
popped = fruits.pop() # Remove last
fruits.sort() # Sort
fruits.reverse() # Reverse
print(len(fruits)) # Length
print("Mango" in fruits) # True — check membership
# List Comprehension — One-liner loop!
squares = [x**2 for x in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Q1. Find the second largest number in a list. Medium
nums = [45, 12, 78, 34, 90, 23]
unique = list(set(nums))
unique.sort()
print(f"Second largest: {unique[-2]}") # 78
Q2. Find all prime numbers between 1-50 using list comprehension. Hard
primes = [n for n in range(2, 51)
if all(n % i != 0 for i in range(2, int(n**0.5)+1))]
print(primes)
# Tuple — cannot be changed (immutable)!
colors = ("Red", "Green", "Blue")
print(colors[0]) # Red
print(len(colors)) # 3
# Tuple unpacking
x, y, z = colors
print(x, y, z) # Red Green Blue
# Single element tuple — must add comma!
single = (42,) # ✅ Tuple
not_tuple = (42) # ❌ Just an integer
# Tuple as dictionary key (list cannot be a key!)
locations = {(28.6, 77.2): "Delhi", (19.0, 72.8): "Mumbai"}
# Set — automatically removes duplicates!
nums = {1, 2, 3, 3, 4, 4, 5}
print(nums) # {1, 2, 3, 4, 5}
# Set operations
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
print(a | b) # Union: {1,2,3,4,5,6,7,8}
print(a & b) # Intersection: {4, 5}
print(a - b) # Difference: {1, 2, 3}
print(a ^ b) # Symmetric diff: {1,2,3,6,7,8}
# Remove duplicates from list — Set trick!
my_list = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(my_list))
print(unique) # [1, 2, 3, 4]
# Creating dictionary
student = {
"name": "Himanshu",
"age": 20,
"course": "B.Tech",
"cgpa": 8.5,
"skills": ["Python", "JavaScript", "SQL"]
}
# Access values
print(student["name"]) # Himanshu
print(student.get("age")) # 20
print(student.get("phone", "Not found")) # Not found
# Add/Update
student["city"] = "Delhi" # Add new
student["age"] = 21 # Update
student.update({"phone": "9999999999"})
# Loop through dictionary
for key, value in student.items():
print(f"{key}: {value}")
# Dictionary Comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1:1, 2:4, 3:9, 4:16, 5:25}
# Nested Dictionary
students = {
"student1": {"name": "Rahul", "marks": 85},
"student2": {"name": "Priya", "marks": 92},
}
print(students["student2"]["name"]) # Priya
Q1. Count how many times each character appears in a string using a dictionary. Medium
text = "hello world"
freq = {}
for char in text:
freq[char] = freq.get(char, 0) + 1
print(freq) # {'h':1,'e':1,'l':3,'o':2,' ':1,'w':1,'r':1,'d':1}
# Writing to a file
with open("notes.txt", "w") as f:
f.write("Hello from PyMaster!\n")
f.write("Python is awesome! 🐍\n")
# Reading a file
with open("notes.txt", "r") as f:
content = f.read()
print(content)
# Append to file
with open("notes.txt", "a") as f:
f.write("New line added!\n")
# Read line by line
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
# Working with CSV
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Himanshu", 20, "Delhi"])
# Working with JSON
import json
data = {"name": "Himanshu", "skills": ["Python", "JS"]}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded["name"]) # Himanshu
with statement! This closes the file automatically —
prevents memory leaks.# Basic try/except
try:
num = int(input("Enter number: "))
result = 100 / num
print(f"Result: {result}")
except ValueError:
print("❌ Please enter a valid number!")
except ZeroDivisionError:
print("❌ Cannot divide by zero!")
except Exception as e:
print(f"❌ Error: {e}")
else:
print("✅ No errors occurred!")
finally:
print("🔄 This always runs!")
# Custom Exception
class AgeError(Exception):
pass
def check_age(age):
if age < 0:
raise AgeError("Age cannot be negative!")
if age > 150:
raise AgeError("Age seems unrealistic!")
print(f"Age {age} is valid ✅")
try:
check_age(-5)
except AgeError as e:
print(f"Error: {e}")
Q1. Create a calculator that handles divide by zero and invalid input. Medium
try:
a = float(input("Number 1: "))
b = float(input("Number 2: "))
op = input("Operation (+,-,*,/): ")
if op == '+': print(a + b)
elif op == '-': print(a - b)
elif op == '*': print(a * b)
elif op == '/': print(a / b)
except ZeroDivisionError: print("Cannot divide by zero!")
except ValueError: print("Invalid number!")
In OOP, we represent real-world things in code using Classes (blueprint) and Objects (actual thing).
# Define a Class
class Student:
def __init__(self, name, age, course):
self.name = name
self.age = age
self.course = course
def introduce(self):
print(f"Hi! I'm {self.name}, {self.age} yrs, studying {self.course}")
def is_adult(self):
return self.age >= 18
# Create Objects
s1 = Student("Himanshu", 20, "B.Tech")
s2 = Student("Priya", 17, "12th")
s1.introduce() # Hi! I'm Himanshu, 20 yrs, studying B.Tech
print(s1.is_adult()) # True
print(s2.is_adult()) # False
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return f"{self.name} says: Woof! 🐕"
class Cat(Animal):
def speak(self):
return f"{self.name} says: Meow! 🐱"
# Polymorphism — same method, different behavior!
animals = [Dog("Buddy"), Cat("Whiskers"), Dog("Max")]
for animal in animals:
print(animal.speak())
# Buddy says: Woof! 🐕
# Whiskers says: Meow! 🐱
# Max says: Woof! 🐕
Q1. Create a BankAccount class with deposit, withdraw, and check balance methods. Hard
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited ₹{amount}. Balance: ₹{self.balance}")
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds! ❌")
else:
self.balance -= amount
print(f"Withdrew ₹{amount}. Balance: ₹{self.balance}")
acc = BankAccount("Himanshu", 1000)
acc.deposit(500) # Balance: ₹1500
acc.withdraw(200) # Balance: ₹1300