Lesson 1: Introduction to Python
1.2 Installing Python
Python can be installed from python.org. IDEs like VS Code, PyCharm, or Jupyter Notebook can be used for coding.
Explanation:-
No code for this topic.1.3 Hello World
The first program prints text to the screen using the print() function.
print("Hello World")
Explanation:-
print() outputs the text "Hello World" to the console.1.4 Python Comments
Comments are used to explain code and are ignored by the interpreter.
# This is a comment
print("Hello")
Explanation:-
Lines starting with # are ignored. Only print("Hello") executes.1.5 Variables
Variables store data values and can be named anything following Python naming rules.
x = 10
y = "Kapil"
print(x, y)
Explanation:-
x stores integer 10, y stores string "Kapil". print() displays both values.1.6 Data Types
Python has several built-in data types like int, float, string, and boolean.
a = 10
b = 3.5
c = "Hello"
d = True
print(type(a), type(b), type(c), type(d))
Explanation:-
type() function shows the data type of each variable.Lesson 2: Python Syntax & Loops
2.7 Type Conversion
Convert between data types using int(), float(), str(), etc.
x = "10"
y = int(x)
print(y + 5)
Explanation:-
x is string "10". int(x) converts it to integer 10. 10 + 5 = 15 is printed.2.8 Input from User
Use input() function to take input from users.
name = input("Enter your name: ")
print("Hello", name)
Explanation:-
input() displays a prompt and waits for user input. The entered value is stored in name.2.9 Arithmetic Operators
Python supports +, -, *, /, %, **, //.
a = 10
b = 3
print(a+b, a-b, a*b, a/b, a%b, a**b, a//b)
Explanation:-
Demonstrates addition, subtraction, multiplication, division, modulus, exponent, and floor division.2.10 Comparison Operators
Used to compare values: ==, !=, >, <, >=, <=
x = 5
y = 10
print(x==y, x!=y, x>y, x<y)
Explanation:-
Compares x and y: equality, inequality, greater than, less than. Returns True or False.2.11 Logical Operators
Combine conditions using and, or, not.
x = True
y = False
print(x and y, x or y, not x)
Explanation:-
and returns True if both True, or returns True if any True, not inverts Boolean value.2.12 If Statement
Executes code if condition is True.
x = 10
if x > 5:
print("Greater than 5")
Explanation:-
Checks if x>5. If True, prints the message.2.13 If-Else Statement
Execute one block if True, another if False.
x = 2
if x > 5:
print("Greater")
else:
print("Smaller")
Explanation:-
If x>5, prints "Greater". Else, prints "Smaller".2.14 Elif Statement
Check multiple conditions using elif.
x = 10
if x < 5:
print("Less")
elif x==10:
print("Equal to 10")
else:
print("Greater")
Explanation:-
First condition False, second True, so "Equal to 10" is printed.2.15 For Loop
Used to iterate over a sequence.
for i in range(5):
print(i)
Explanation:-
range(5) generates numbers 0 to 4. Loop prints each number on a new line.2.16 While Loop
Repeats code while condition is True.
i = 0
while i < 5:
print(i)
i += 1
Explanation:-
Starts i=0. Prints i and increments by 1 until i<5 is False.2.17 Break Statement
Stops the loop immediately.
for i in range(10):
if i==5:
break
print(i)
Explanation:-
Loop stops when i==5. Numbers 0-4 are printed.Lesson 3: Python Syntax & Loops
3.18 Continue Statement
Skips the current iteration and continues with the next.
for i in range(5):
if i==2:
continue
print(i)
Explanation:-
When i==2, continue skips printing. Output: 0,1,3,43.19 Lists
Ordered collection of items that can be changed.
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
fruits.append("mango")
Explanation:-
fruits[0] accesses first element. append() adds "mango" at the end.3.20 List Operations
Common operations: append, insert, remove, pop, slicing.
numbers = [1,2,3,4,5]
numbers.append(6)
numbers.pop(0)
print(numbers[1:4])
Explanation:-
append adds 6, pop removes first element, slicing [1:4] prints 2nd to 4th items.3.21 Tuples
Immutable ordered collection of items.
t = (1, 2, 3)
print(t[0])
Explanation:-
t[0] accesses first element. Tuple cannot be modified.3.22 Tuple Operations
Tuples support indexing and slicing but cannot be modified.
t = (1,2,3)
print(t[1:])
Explanation:-
Slicing t[1:] prints elements from index 1 onward.3.23 Sets
Unordered collection of unique elements.
s = {1,2,3,3,4}
print(s)
Explanation:-
Duplicates removed automatically. Output: {1,2,3,4}3.24 Set Operations
Union, intersection, difference, adding/removing elements.
a = {1,2,3}
b = {2,3,4}
print(a|b, a&b, a-b)
a.add(5)
Explanation:-
a|b union, a&b intersection, a-b difference, add() adds 5 to set a.3.25 Dictionaries
Store key-value pairs.
student = {"id":1,"name":"Kapil"}
print(student["name"])
Explanation:-
Access value using key. student["name"] gives "Kapil".3.26 Dictionary Operations
Access, add, update, delete keys.
student["age"]=25
print(student.get("id"))
del student["name"]
Explanation:-
Adds new key "age", get() retrieves value, del removes key.Lesson 4: Function and Arguments
4.27 Functions
Reusable blocks of code defined with def.
def greet(name):
return "Hello " + name
print(greet("Kapil"))
Explanation:-
Defines greet function that takes name and returns greeting.4.28 Function Parameters
Pass values to functions as parameters.
def add(a,b):
return a+b
print(add(5,3))
Explanation:-
a=5, b=3 passed to add(), returns 8.4.29 Default Arguments
Set default values for parameters.
def greet(name="User"):
print("Hello", name)
greet()
greet("Kapil")
Explanation:-
If no argument given, name="User". Otherwise uses provided argument.4.30 Keyword Arguments
Specify arguments by name when calling a function.
def greet(name, age):
print(name, age)
greet(age=25, name="Kapil")
Explanation:-
Arguments passed by name, order does not matter.4.31 Return Statement
Return values from functions.
def square(x):
return x*x
print(square(5))
Explanation:-
square(5) returns 25. print() displays result.4.32 Lambda Functions
Anonymous one-line functions.
square = lambda x: x*x
print(square(5))
Explanation:-
lambda x:x*x creates function to square a number.4.33 Map Function
Apply a function to all items in a list.
nums = [1,2,3]
squared = list(map(lambda x:x*x, nums))
print(squared)
Explanation:-
map applies lambda to each list element. Result converted to list.4.34 Filter Function
Filter items based on a condition.
nums = [1,2,3,4,5]
even = list(filter(lambda x:x%2==0, nums))
print(even)
Explanation:-
filter keeps elements satisfying condition x%2==0.4.35 Reduce Function
Apply function cumulatively to items (from functools).
from functools import reduce
nums=[1,2,3,4]
sum = reduce(lambda x,y:x+y, nums)
print(sum)
Explanation:-
reduce applies lambda cumulatively: (((1+2)+3)+4)=10.Lesson 5: String, Files and Module
5.36 String Basics
Strings are sequences of characters.
s = "Hello"
print(s[0], s[1:4])
Explanation:-
s[0] is first character H. s[1:4] slices from index 1 to 3.5.37 String Methods
Common methods: lower, upper, replace, split, join.
s="Hello World"
print(s.lower(), s.upper(), s.replace("World","Kapil"))
Explanation:-
lower() converts to lowercase, upper() uppercase, replace changes substring.5.38 f-Strings
Embed variables in strings easily.
name="Kapil"
age=25
print(f"My name is {name} and age is {age}")
Explanation:-
f-string evaluates variables in {} and inserts into string.5.39 String Membership
Check if substring exists.
s="Hello"
print("H" in s, "X" not in s)
Explanation:-
"H" in s returns True, "X" not in s returns True.5.40 File Handling Basics
Read and write files using open().
f = open("file.txt","w")
f.write("Hello World")
f.close()
Explanation:-
Open file in write mode, write text, then close file.5.41 Reading Files
Read files using read(), readline(), readlines().
f = open("file.txt","r")
print(f.read())
f.close()
Explanation:-
Read entire content of file and print.5.42 With Statement
Automatically closes files after block execution.
with open("file.txt","r") as f:
print(f.read())
Explanation:-
with ensures file is closed after block. Read content and print.5.43 Modules
Python files that can be imported.
import math
print(math.sqrt(16))
Explanation:-
import math allows access to math module functions. sqrt(16) returns 4.5.44 Random Module
Generate random numbers and choices.
import random
print(random.randint(1,10))
Explanation:-
randint generates a random integer between 1 and 10.5.45 Math Module
Mathematical functions like sqrt, pow, ceil, floor.
import math
print(math.ceil(4.2), math.floor(4.8))
Explanation:-
ceil rounds up, floor rounds down.5.46 Datetime Module
Work with dates and times.
import datetime
now = datetime.datetime.now()
print(now)
Explanation:-
datetime.now() returns current date and time.Lesson 6: Exceptions, Clause and OOPs
6.47 Exception Handling
Handle runtime errors using try-except.
try:
x = 10/0
except ZeroDivisionError:
print("Cannot divide by zero")
Explanation:-
try block executes code; except catches division by zero and prints message.6.48 Finally Clause
Code that always runs, whether exception occurs or not.
try:
x = 10/0
except ZeroDivisionError:
print("Error")
finally:
print("End")
Explanation:-
finally block executes regardless of exception.6.49 Raising Exceptions
Manually raise exceptions using raise.
x = -5
if x<0:
raise ValueError("x cannot be negative")
Explanation:-
raise triggers ValueError with custom message.6.50 Object-Oriented Programming
Python supports classes and objects.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Kapil",25)
print(p.name,p.age)
Explanation:-
Defines class Person with constructor __init__. Creates object p with attributes name and age, then prints them.Lesson 7: Class Methods
7.51 Class Methods
Class methods are defined with @classmethod decorator and take cls as first parameter.
class Person:
count = 0
@classmethod
def increase_count(cls):
cls.count += 1
Person.increase_count()
print(Person.count)
Explanation:-
increase_count is a class method that modifies class-level variable count. cls refers to class, not instance.7.52 Static Methods
Static methods are defined with @staticmethod and do not take self or cls.
class Math:
@staticmethod
def add(a,b):
return a+b
print(Math.add(5,3))
Explanation:-
add() is static; can be called on class without creating object.7.53 Instance Methods
Regular methods with self parameter operate on object instances.
class Person:
def __init__(self,name):
self.name=name
def greet(self):
print("Hello",self.name)
p=Person("Kapil")
p.greet()
Explanation:-
self refers to the object instance. greet() prints the name of that object.7.54 Encapsulation
Hide data using private attributes with double underscore __.
class Person:
def __init__(self,name):
self.__name=name
def get_name(self):
return self.__name
p=Person("Kapil")
print(p.get_name())
Explanation:-
__name is private; get_name() is used to access it. Prevents direct modification.7.55 Inheritance
A class can inherit properties and methods from another class.
class Person:
def greet(self):
print("Hello")
class Student(Person):
pass
s=Student()
s.greet()
Explanation:-
Student inherits greet() method from Person class. s.greet() prints Hello.7.56 Multiple Inheritance
A class can inherit from multiple classes.
class A:
def a_method(self):
print("A")
class B:
def b_method(self):
print("B")
class C(A,B):
pass
c=C()
c.a_method()
c.b_method()
Explanation:-
C inherits methods from both A and B; can call both a_method() and b_method().7.57 Polymorphism
Same method name behaves differently in different classes.
class Dog:
def speak(self):
print("Woof")
class Cat:
def speak(self):
print("Meow")
for animal in [Dog(), Cat()]:
animal.speak()
Explanation:-
Both Dog and Cat have speak(), but output differs based on object type.7.58 Magic Methods
Special methods starting and ending with __ to customize behavior.
class Number:
def __init__(self,x):
self.x=x
def __add__(self,other):
return self.x+other.x
n1=Number(5)
n2=Number(10)
print(n1+n2)
Explanation:-
__add__ defines behavior for + operator. n1+n2 calls n1.__add__(n2), returns 15.7.59 Property Decorator
Use @property to access methods like attributes.
class Person:
def __init__(self,name):
self._name=name
@property
def name(self):
return self._name
p=Person("Kapil")
print(p.name)
Explanation:-
name() method accessed like attribute due to @property.7.60 Iterators
Objects that can be iterated using iter() and next().
lst=[1,2,3]
it=iter(lst)
print(next(it))
print(next(it))
Explanation:-
iter(lst) creates iterator; next() returns next element sequentially.Lesson 8: Generator and Comprehensions
8.61 Generators
Functions that yield values one at a time using yield.
def gen():
for i in range(3):
yield i
for val in gen():
print(val)
Explanation:-
yield pauses function and returns value. Next iteration resumes from last yield.8.62 Generator Expressions
Compact way to create generators using parentheses.
squared=(x*x for x in range(5))
for val in squared:
print(val)
Explanation:-
Generates squares lazily, one by one, saving memory.8.63 List Comprehensions
Create lists in a single line.
nums=[1,2,3,4]
squares=[x*x for x in nums]
print(squares)
Explanation:-
Iterates nums, squares each element, returns list [1,4,9,16].8.64 Dictionary Comprehensions
Create dictionaries in one line.
nums=[1,2,3]
squared={x:x*x for x in nums}
print(squared)
Explanation:-
Keys are numbers, values are their squares. Output: {1:1,2:4,3:9}8.65 Set Comprehensions
Create sets using comprehension.
nums=[1,2,2,3]
squares={x*x for x in nums}
print(squares)
Explanation:-
Removes duplicates automatically. Output: {1,4,9}8.66 Decorators
Functions that modify behavior of other functions.
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@decorator
def say():
print("Hello")
say()
Explanation:-
say() is wrapped; prints Before, Hello, After.8.67 Modules
Python files that can be imported to reuse code.
import math
print(math.factorial(5))
Explanation:-
math module factorial(5) computes 5!.8.68 Packages
Folders containing multiple Python modules with __init__.py.
import os
print(os.getcwd())
Explanation:-
os package provides functions to interact with OS. getcwd() returns current working directory.8.69 ? Multiclass Logistic Regression — One-vs-Rest (OvR) and One-vs-One (OvO)
Concept:
Logistic Regression is primarily used for binary classification. However, in real-world scenarios, we often need to classify data into more than two classes. For example, predicting the type of product purchased: Electronics, Clothing, or Grocery.
To handle multiple classes, two main strategies are used:
1️⃣ One-vs-Rest (OvR) — Also called One-vs-All. The model trains one classifier per class, treating that class as “1” and all others as “0.” The class with the highest probability wins.
2️⃣ One-vs-One (OvO) — This approach builds a classifier for every possible pair of classes. If there are 3 classes, it builds 3 classifiers (A vs B, B vs C, A vs C). The class that wins the most pairwise comparisons is predicted.
Let’s see this in action using a dataset with three categories: Electronics, Grocery, and Clothing.
Logistic Regression is primarily used for binary classification. However, in real-world scenarios, we often need to classify data into more than two classes. For example, predicting the type of product purchased: Electronics, Clothing, or Grocery.
To handle multiple classes, two main strategies are used:
1️⃣ One-vs-Rest (OvR) — Also called One-vs-All. The model trains one classifier per class, treating that class as “1” and all others as “0.” The class with the highest probability wins.
2️⃣ One-vs-One (OvO) — This approach builds a classifier for every possible pair of classes. If there are 3 classes, it builds 3 classifiers (A vs B, B vs C, A vs C). The class that wins the most pairwise comparisons is predicted.
Let’s see this in action using a dataset with three categories: Electronics, Grocery, and Clothing.
# Multiclass Logistic Regression Example
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report, confusion_matrix
# Load the dataset
df = pd.read_csv("multiclass_product_data.csv")
print(df.head())
# Encode categorical variables
df = pd.get_dummies(df, columns=["Product_Category", "Store_Size"], drop_first=True)
# Define features and target
X = df.drop("Target_Product_Type", axis=1)
y = df["Target_Product_Type"]
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Feature scaling
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Train One-vs-Rest Logistic Regression
ovr_model = LogisticRegression(multi_class="ovr", solver="liblinear")
ovr_model.fit(X_train_scaled, y_train)
y_pred_ovr = ovr_model.predict(X_test_scaled)
# Train One-vs-One Logistic Regression
ovo_model = LogisticRegression(multi_class="ovo", solver="liblinear")
ovo_model.fit(X_train_scaled, y_train)
y_pred_ovo = ovo_model.predict(X_test_scaled)
# Evaluate both models
print("One-vs-Rest Classification Report:")
print(classification_report(y_test, y_pred_ovr))
print("One-vs-One Classification Report:")
print(classification_report(y_test, y_pred_ovo))
# Confusion Matrix for OvR
cm_ovr = confusion_matrix(y_test, y_pred_ovr)
print("Confusion Matrix (OvR):")
print(cm_ovr)
Explanation:-
✅ Code Explanation: 1️⃣ We load the multiclass_product_data.csv dataset, which includes products from multiple categories.2️⃣ We perform one-hot encoding on categorical features like Product_Category and Store_Size.
3️⃣ The target variable Target_Product_Type contains three classes — Electronics, Grocery, and Clothing.
4️⃣ Two models are trained:
• OvR: One model per class.
• OvO: One model per pair of classes.
5️⃣ After prediction, both models are evaluated using classification_report and confusion_matrix.
6️⃣ You can compare precision, recall, and F1-score for each class to determine which strategy performs better.
? Conclusion:
For small datasets — OvO works well but may take more time.
For larger datasets — OvR is faster and typically sufficient for most business problems.
Lesson 11: Modules, Packages & Virtual Environments
11.70 Regular Expressions
Pattern matching using re module.
import re
pattern="a.*b"
text="acb"
if re.match(pattern,text):
print("Match")
Explanation:-
Matches string starting with a and ending with b. re.match() checks pattern at beginning.11.71 JSON Handling
Read and write JSON data using json module.
import json
data={"name":"Kapil","age":25}
json_str=json.dumps(data)
print(json_str)
Explanation:-
dumps() converts dictionary to JSON string.11.72 Command Line Arguments
Access arguments passed to script via sys.argv.
import sys
print(sys.argv)
Explanation:-
sys.argv is list of command-line arguments. argv[0] is script name.11.73 OS Module
Interact with operating system: files, directories.
import os
print(os.listdir("."))
Explanation:-
listdir(".") lists files in current directory.11.74 Shutil Module
High-level file operations like copy, move.
import shutil
shutil.copy("file1.txt","file2.txt")
Explanation:-
Copies file1.txt to file2.txt.Lesson 12: Object-Oriented Programming
12.75 Pickle Module
Serialize and deserialize Python objects.
import pickle
data={"name":"Kapil"}
with open("data.pkl","wb") as f:
pickle.dump(data,f)
Explanation:-
dump() writes object to file in binary format.12.76 Virtual Environments
Isolate project dependencies using venv.
python -m venv myenv
Explanation:-
Creates a folder myenv with separate Python environment.12.77 Installing Packages
Use pip to install external packages.
pip install requests
Explanation:-
Installs requests library for HTTP requests.12.78 Requests Module
Send HTTP requests in Python.
import requests
r=requests.get("https://api.github.com")
print(r.status_code)
Explanation:-
get() sends GET request. status_code shows response code.12.79 Web Scraping Basics
Use BeautifulSoup to parse HTML.
from bs4 import BeautifulSoup
html="<p>Hello</p>"
soup=BeautifulSoup(html,"html.parser")
print(soup.p.text)
Explanation:-
soup.p accessestag; .text gets content "Hello".
12.80 CSV Files
Read and write CSV using csv module.
import csv
with open("data.csv","w",newline="") as f:
writer=csv.writer(f)
writer.writerow(["Name","Age"])
Explanation:-
Writes a header row to data.csv.12.81 Pandas DataFrame Basics
Create and manipulate tabular data.
import pandas as pd
df=pd.DataFrame({"Name":["Kapil","Amit"],"Age":[25,30]})
print(df)
Explanation:-
DataFrame is table with rows and columns.Lesson 13: File I/O, JSON, and CSV Handling
13.82 Accessing DataFrame Rows/Columns
Use loc, iloc, and column names.
print(df["Name"])
print(df.iloc[0])
Explanation:-
df["Name"] accesses column; iloc[0] accesses first row.13.83 Filtering DataFrame
Filter rows based on conditions.
print(df[df["Age"]>25])
Explanation:-
Selects rows where Age>25.13.84 Adding Columns
Add new column by assignment.
df["Country"]="India"
print(df)
Explanation:-
Adds Country column with same value "India" to all rows.13.85 Dropping Columns/Rows
Use drop() method.
df.drop("Country",axis=1,inplace=True)
print(df)
Explanation:-
Drops Country column. axis=1 specifies column, inplace modifies df.13.86 Handling Missing Data
Use dropna() or fillna() methods.
df.fillna(0,inplace=True)
Explanation:-
Replaces all NaN values with 0.13.87 GroupBy in Pandas
Aggregate data by group.
df.groupby("Age").count()
Explanation:-
Groups rows by Age and counts occurrences in each group.Lesson 14: Advanced Python Topics
14.88 Iterating DataFrame
Loop through rows using iterrows().
for index,row in df.iterrows():
print(row["Name"],row["Age"])
Explanation:-
iterrows() returns index and row. Access values using column names.14.89 Matplotlib Basics
Plot graphs using matplotlib.
import matplotlib.pyplot as plt
plt.plot([1,2,3],[4,5,6])
plt.show()
Explanation:-
Plots line graph with x=[1,2,3] and y=[4,5,6].14.90 Bar Charts
Visualize data as bars.
plt.bar(["A","B"],[10,20])
plt.show()
Explanation:-
Bar chart shows A=10, B=20.14.91 Histograms
Visualize distribution of numeric data.
plt.hist([1,2,2,3,3,3,4])
plt.show()
Explanation:-
Histogram bins show frequency of numbers.14.92 Seaborn Basics
High-level visualization library built on matplotlib.
import seaborn as sns
sns.histplot([1,2,2,3,3,3,4])
Explanation:-
Creates histogram using Seaborn with default styling.14.93 Simple Project - Calculator
Build calculator using functions.
def add(a,b): return a+b
print(add(5,3))
Explanation:-
Defines add() function and prints result 8.14.94 Simple Project - Number Guessing
Guess number game using random.
import random
num=random.randint(1,10)
guess=int(input("Enter:"))
if guess==num:
print("Correct")
Explanation:-
Generates random number 1-10. Checks if user guess matches number.Lesson 15: Python Projects and Applications
15.95 Simple Project - To-Do List
Manage tasks using lists.
tasks=[]
tasks.append("Study Python")
print(tasks)
Explanation:-
Adds task to list and prints current tasks.15.96 Simple Project - Contact Book
Store contacts using dictionary.
contacts={}
contacts["Kapil"]="9876543210"
print(contacts)
Explanation:-
Dictionary stores name as key, number as value.15.97 Simple Project - Text Analyzer
Count words and letters in text.
text="Hello World"
print(len(text.split()),len(text))
Explanation:-
split() creates list of words. len() counts words and characters.15.98 Simple Project - File Organizer
Move files into folders based on type.
import os,shutil
for f in os.listdir("."):
if f.endswith(".txt"):
shutil.move(f,"TextFiles/")
Explanation:-
Loops files in directory. Moves .txt files to folder TextFiles.15.99 Best Practices
Write readable and maintainable code.
x=10
y=20
sum=x+y
print(sum)
Explanation:-
Use meaningful variable names and proper indentation.15.100 Next Steps
After mastering basics, learn OOP deeply, modules, libraries like Pandas, Matplotlib, and start projects.
Comments (0)
Login to comment