Python Programming
(Basic to advance)
8/17/2025 Shiv Laxmi Commercial Institute 1
Python
Python is a simple and powerful programming
language that is easy to learn.
Its syntax is close to human language, so it is
beginner-friendly.
It is used in many fields like web development,
data science, machine learning, and automation.
Python requires less code compared to other
languages because of its simplicity.
It has a huge community and many libraries that
make problem-solving faster.
In short, Python is like a universal tool to quickly
turn ideas into real working programs.
8/17/2025 Shiv Laxmi Commercial Institute 2
How python was developed?
Python was created by Guido van Rossum in
the late 1980s at CWI, Netherlands. He wanted
a simple, readable, and powerful language
inspired by ABC but more practical. During
Christmas 1989, he began developing it as a
hobby and named it Python after Monty
Python’s Flying Circus. The first version came
out in 1991 with core features like functions
and loops. Over time, with Python 2 (2000) and
Python 3 (2008), it became one of the world’s
most popular programming languages, widely
used in web development, AI, data science, and
automation.
8/17/2025 Shiv Laxmi Commercial Institute 3
Print “Hello World”
print("Hello, World!")
Output
Hello, World!
8/17/2025 Shiv Laxmi Commercial Institute 4
Variables
A variable is like a container or a box
that stores data (numbers, text, etc.).
You can give this container a name so
that you can use it later in your program.
In Python, you don’t need to declare the
type (like int, float, string) — Python
figures it out automatically.
A variable’s value can be changed anytime
during the program.
8/17/2025 Shiv Laxmi Commercial Institute 5
Variables coding example
# assigning values to variables
name = "John"
age = 25
height = 5.9
print(name) # Output: John
print(age) # Output: 25
print(height) # Output: 5.9
8/17/2025 Shiv Laxmi Commercial Institute 6
Value Overriding
In Python, when you assign a new
value to the same variable name, the
old value gets replaced (overridden).
This means the variable now points to the
new value, and the previous value is lost
(unless stored somewhere else).
8/17/2025 Shiv Laxmi Commercial Institute 7
Getting the data type
In Python, you can find the type of a
variable using the built-in type() function.
Example:
x = 10
y = 5.5
z = "Hello"
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'float'>
print(type(z)) # Output: <class 'str'>
8/17/2025 Shiv Laxmi Commercial Institute 8
Comments
A comment is a line in the code that
Python ignores when running the
program.
We use comments to explain what the
code does, make notes, or leave
reminders.
They make programs easier to read and
understand for humans.
8/17/2025 Shiv Laxmi Commercial Institute 9
Types of comments
Single line comment Multi line comment
Single-line Multi-line comment
comment → Start → Use triple quotes
with # (''' or """)
8/17/2025 Shiv Laxmi Commercial Institute 10
Single line comment code example
# This is a single-line comment
x = 10 # Assigning 10 to variable x
print(x)
8/17/2025 Shiv Laxmi Commercial Institute 11
Multi line comment
'''
This is a multi-line comment.
It can span multiple lines.
Useful for explanations.
'''
print("Hello, World!")
8/17/2025 Shiv Laxmi Commercial Institute 12
Python String
A string is a sequence of characters
(letters, numbers, symbols, or spaces)
enclosed in quotes.
In Python, you can use single quotes ' ',
double quotes " ", or triple quotes '''
''' / """ """ to create strings.
8/17/2025 Shiv Laxmi Commercial Institute 13
How to create strings
# Different ways to create strings
s1 = 'Hello'
s2 = "World"
s3 = '''This is
a multi-line
string'''
print(s1)
print(s2)
print(s3)
8/17/2025 Shiv Laxmi Commercial Institute 14
Slicing strings
Slicing means extracting a part (substring)
from a string using index ranges.
Syntax:
string[start:end:step]
start → index where slicing begins (inclusive).
end → index where slicing stops (exclusive).
step → how many steps to move (default is
1).
8/17/2025 Shiv Laxmi Commercial Institute 15
Slicing string coding example
# String Slicing Examples
text = "PythonProgramming"
print("Original String:", text)
# 1. Basic slicing
print("text[0:6] ->", text[0:6]) # Python
print("text[6:] ->", text[6:]) # Programming
print("text[:6] ->", text[:6]) # Python
# 2. Negative indexing
print("text[-11:-1] ->", text[-11:-1]) # rogrammin
print("text[-7:] ->", text[-7:]) # grammin
# 3. Using step
print("text[0:14:2] ->", text[0:14:2]) # Pto rgamn
print("text[::3] ->", text[::3]) # PhPgmi
8/17/2025 Shiv Laxmi Commercial Institute 16
Python Tuple
A tuple is a collection of items (like a list)
but immutable (you cannot change, add,
or remove elements once created).
Tuples are written inside round brackets
().
They can store different types of data
(numbers, strings, lists, etc.).
8/17/2025 Shiv Laxmi Commercial Institute 17
Tuple code example
# Creating a tuple
my_tuple = (10, 20, 30, "Hello", 5.5)
print(my_tuple) # (10, 20, 30, 'Hello', 5.5)
print(type(my_tuple)) # <class 'tuple'>
# Accessing elements
print(my_tuple[0]) # 10 (first element)
print(my_tuple[-1]) # 5.5 (last element)
# Slicing
print(my_tuple[1:4]) # (20, 30, 'Hello')
8/17/2025 Shiv Laxmi Commercial Institute 18
Unpacking Tuple
# Packing
person = ("Alice", 25, "Engineer")
# Unpacking
name, age, job = person
print(name) # Alice
print(age) # 25
print(job) # Engineer
8/17/2025 Shiv Laxmi Commercial Institute 19
Example: Convert Tuple → List →
Modify → Convert Back to Tuple
# Original tuple
my_tuple = (10, 20, 30, "Hello")
# Convert tuple to list
my_list = list(my_tuple)
print("Converted List:", my_list)
# Modify the list
my_list[1] = 200 # Change value at index 1
my_list.append("Python") # Add a new item
my_list.remove(30) # Remove an item
print("Modified List:", my_list)
# Convert back to tuple
new_tuple = tuple(my_list)
print("New Tuple:", new_tuple)
8/17/2025 Shiv Laxmi Commercial Institute 20
Output
Converted List: [10, 20, 30, 'Hello']
Modified List: [10, 200, 'Hello', 'Python']
New Tuple: (10, 200, 'Hello', 'Python')
This way you can change values inside a tuple indirectly:
Convert it into a list.
Make changes (add, update, remove).
Convert back into a tupl
8/17/2025 Shiv Laxmi Commercial Institute 21
Python Loop
A loop is used to repeat a block of code
multiple times until a condition is met.
Instead of writing the same code again and
again, you use a loop.
8/17/2025 Shiv Laxmi Commercial Institute 22
Loops
For loop While loop
for loop while loop
Used to iterate (go Repeats a block of
through) a sequence code as long as a
like list, tuple, string, condition is true.
or range.
8/17/2025 Shiv Laxmi Commercial Institute 23
for loop code example
for i in range(5):
print("Hello", i)
Output:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
8/17/2025 Shiv Laxmi Commercial Institute 24
While loop code example
count = 1
while count <= 5:
print("Count:", count)
count += 1
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
8/17/2025 Shiv Laxmi Commercial Institute 25
Python OOPs concept
OOP (Object-Oriented Programming) is a
way of structuring programs by bundling
data (variables) and functions
(methods) together into objects.
Instead of writing everything separately,
OOP lets us model real-world things
(like a Car, Student, Bank Account) in
code.
8/17/2025 Shiv Laxmi Commercial Institute 26
1. Class
Class
A blueprint for creating objects.
It defines variables (attributes) and
functions (methods).
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def show(self):
print("Car:", self.brand, self.model)
8/17/2025 Shiv Laxmi Commercial Institute 27
2. Object
Object
An instance of a class (a real entity
created from the blueprint).
car1 = Car("Toyota", "Fortuner")
car2 = Car("Tesla", "Model S")
car1.show() # Car: Toyota Fortuner
car2.show() # Car: Tesla Model S
8/17/2025 Shiv Laxmi Commercial Institute 28
3. Encapsulation
Wrapping data (variables) and methods
inside a class.
Controls access using private (__var),
protected (_var), or public variables.
class Student:
def __init__(self, name, marks):
self.__name = name # private variable
self.marks = marks
def show(self):
print("Student:", self.__name, "Marks:", self.marks)
s1 = Student("Alice", 85)
s1.show()
8/17/2025 Shiv Laxmi Commercial Institute 29
4.Inheritance
Inheritance
A class can inherit properties and
methods from another class.
Promotes code reusability.
class Animal:
def speak(self):
print("This is an animal.")
class Dog(Animal): # Inherits from Animal
def speak(self):
print("Bark!")
d = Dog()
d.speak() # Bark!
8/17/2025 Shiv Laxmi Commercial Institute 30
5.Polymorphism
Polymorphism
One method can have different behaviors
depending on the object
class Cat:
def sound(self):
return "Meow"
class Dog:
def sound(self):
return "Bark"
# Same method, different behavior
for animal in (Cat(), Dog()):
print(animal.sound())
8/17/2025 Shiv Laxmi Commercial Institute 31
Python Mathematics
Basic Arithmetic Operators
Python supports all basic math operations:
a = 10
b=3
print(a + b) # Addition → 13
print(a - b) # Subtraction → 7
print(a * b) # Multiplication → 30
print(a / b) # Division → 3.333...
print(a // b) # Floor Division → 3
print(a % b) # Modulus (remainder) → 1
print(a ** b) # Exponentiation → 1000 (10³)
8/17/2025 Shiv Laxmi Commercial Institute 32
2. Built-in math Module
Python has a math library that gives extra mathematical
functions
import math
print(math.sqrt(16)) # Square root → 4.0
print(math.pow(2, 3)) # Power → 8.0
print(math.factorial(5)) # Factorial → 120
print(math.gcd(12, 18)) # Greatest Common Divisor → 6
8/17/2025 Shiv Laxmi Commercial Institute 33
Trigonometry Functions
import math
print(math.sin(math.pi/2)) # 1.0
print(math.cos(0)) # 1.0
print(math.tan(math.pi/4)) # 1.0
8/17/2025 Shiv Laxmi Commercial Institute 34
Rounding Numbers
print(round(3.14159, 2)) # 3.14
print(math.ceil(4.3)) # 5 (round up)
print(math.floor(4.7)) # 4 (round down)
8/17/2025 Shiv Laxmi Commercial Institute 35
Constants in math
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
Shiv Laxmi Commercial Institute 36
8/17/2025
Pandas
Pandas is a powerful Python library for
data analysis and manipulation.
It is built on top of NumPy and is widely
used in data science, machine
learning, and finance.
Pandas provides two main data
structures:
Series → 1D (like a column in Excel).
DataFrame → 2D (like a full Excel table)
8/17/2025 Shiv Laxmi Commercial Institute 37
Pandas Series (1D data)
import pandas as pd
# Creating a Series
data = [10, 20, 30, 40]
s = pd.Series(data)
print(s)
0 10
1 20
2 30
3 40
dtype: int64
8/17/2025 Shiv Laxmi Commercial Institute 38
Pandas DataFrame (2D data)
import pandas as pd
# Dictionary → DataFrame
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"City": ["Delhi", "Mumbai", "Kolkata"]
}
df = pd.DataFrame(data)
print(df)
8/17/2025 Shiv Laxmi Commercial Institute 39
Output:
Name Age City
0 Alice 25 Delhi
1 Bob 30 Mumbai
2 Charlie 35 Kolkata
8/17/2025 Shiv Laxmi Commercial Institute 40
Birthday Party Expense DataFrame using Pandas
import pandas as pd
# Birthday Party Expenses
data = {
"Item": ["Cake", "Decorations", "Food & Drinks", "Music/DJ", "Return Gifts",
"Venue", "Photography"],
"Quantity": [1, 50, 100, 1, 30, 1, 1],
"Cost_per_unit": [1200, 20, 150, 5000, 100, 8000, 4000]
}
# Create DataFrame
df = pd.DataFrame(data)
# Calculate total cost for each item
df["Total_Cost"] = df["Quantity"] * df["Cost_per_unit"]
# Calculate grand total
grand_total = df["Total_Cost"].sum()
print(df)
print("\n Total Birthday Party Expense = ₹", grand_total)
8/17/2025 Shiv Laxmi Commercial Institute 41
Output
Item Quantity Cost_per_unit Total_Cost
0 Cake 1 1200 1200
1 Decorations 50 20 1000
2 Food & Drinks 100 150 15000
3 Music/DJ 1 5000 5000
4 Return Gifts 30 100 3000
5 Venue 1 8000 8000
6 Photography 1 4000 4000
Total Birthday Party Expense = ₹ 37000
8/17/2025 Shiv Laxmi Commercial Institute 42
Numpy
NumPy stands for Numerical Python.
It is a Python library used for scientific
and numerical computing.
It is fast because it is written in C and
optimized for large datasets.
It mainly works with arrays, not just
simple lists.
8/17/2025 Shiv Laxmi Commercial Institute 43
Basic Numpy usage
import numpy as np
# Create NumPy array
arr = np.array([10, 20, 30, 40, 50])
print("Array:", arr)
# Array operations
print("Mean:", np.mean(arr)) # Average
print("Sum:", np.sum(arr)) # Total
print("Max:", np.max(arr)) # Maximum
value
print("Square Root:", np.sqrt(arr)) # Square root
of each element
8/17/2025 Shiv Laxmi Commercial Institute 44
Output
Array: [10 20 30 40 50]
Mean: 30.0
Sum: 150
Max: 50
Square Root: [3.16227766 4.47213595
5.47722558 6.32455532 7.07106781]
8/17/2025 Shiv Laxmi Commercial Institute 45
2D Array Matrix
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print("Matrix:\n", matrix)
print("Transpose:\n", matrix.T) #
Transpose of matrix
print("Determinant:",
np.linalg.det(matrix)) # Determinant
8/17/2025 Shiv Laxmi Commercial Institute 46
Output
Matrix:
[[1 2 3]
[4 5 6]
[7 8 9]]
Transpose:
[[1 4 7]
[2 5 8]
[3 6 9]]
Determinant: 0.0
8/17/2025 Shiv Laxmi Commercial Institute 47
Matplotlib
Matplotlib is a Python library for data
visualization.
It is used to create charts like line plots,
bar charts, scatter plots, pie charts,
histograms, etc.
Mostly used along with NumPy and
Pandas for analysis.
8/17/2025 Shiv Laxmi Commercial Institute 48
Code example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y, marker='o', color='blue',
linestyle='--')
plt.title("Line Plot Example")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
8/17/2025 Shiv Laxmi Commercial Institute 49
Bar chart
categories = ['Cake', 'Food', 'Decor',
'Music', 'Gifts']
costs = [1200, 15000, 1000, 5000, 3000]
plt.bar(categories, costs, color='orange')
plt.title("Birthday Party Expenses")
plt.xlabel("Items")
plt.ylabel("Cost in ₹")
plt.show()
8/17/2025 Shiv Laxmi Commercial Institute 50
Pie Chart
plt.pie(costs, labels=categories,
autopct='%1.1f%%', startangle=90)
plt.title("Expense Distribution")
plt.show()
8/17/2025 Shiv Laxmi Commercial Institute 51
Python Turtle
It’s a built-in library (no need to install
separately).
You control a "turtle" (like a pen) that
moves around the screen.
You can make the turtle draw lines,
shapes, or even animations.
8/17/2025 Shiv Laxmi Commercial Institute 52
Draw a square
import turtle
# create a turtle
t = turtle.Turtle()
# draw a square
for i in range(4):
t.forward(100) # move forward 100 units
t.right(90) # turn right 90 degrees
turtle.done()
8/17/2025 Shiv Laxmi Commercial Institute 53
Star
import turtle
t = turtle.Turtle()
for i in range(5):
t.forward(150)
t.right(144) # angle to create star
turtle.done()
8/17/2025 Shiv Laxmi Commercial Institute 54
Thankyou
8/17/2025 Shiv Laxmi Commercial Institute 55