Practical Code Lab (1 to 20)
Simple and student-friendly Python programs. Each practical includes code, syntax highlights, and a short explanation.
Jump To Practical
- Practical 1 - Personalized Greeting
- Practical 2 - Area of Shapes
- Practical 3 - Gross Salary
- Practical 4 - Arithmetic Operations
- Practical 5 - Task List (List and Tuple)
- Practical 6 - Set Operations
- Practical 7 - Student Dictionary
- Practical 8 - Even or Odd
- Practical 9 - Factorial
- Practical 10 - Prime Number
- Practical 11 - Function Calculator
- Practical 12 - File Word Length
- Practical 13 - Create Executable
- Practical 14 - Division with Exception Handling
- Practical 15 - Debugging with pdb
- Practical 16 - Regex Validation
- Practical 17 - Regex Data Extraction
- Practical 18 - NumPy 1D/2D/3D Arrays
- Practical 19 - NumPy Array Operations
- Practical 20 - Basic Statistics
Practical 1: Personalized Greeting
name = input("Enter your name: ")
city = input("Enter your city: ")
print(f"Hello {name}! Welcome from {city}.")
Syntax used: input(), print(), f-string
Explanation: Program takes name and city from user and prints a personalized greeting.
Expected output:
Enter your name: Asha
Enter your city: Mumbai
Hello Asha! Welcome from Mumbai.
Practical 2: Area of Circle, Rectangle, Triangle
pi = 3.14
r = float(input("Radius of circle: "))
print("Area of circle:", pi * r * r)
l = float(input("Length of rectangle: "))
b = float(input("Breadth of rectangle: "))
print("Area of rectangle:", l * b)
base = float(input("Base of triangle: "))
height = float(input("Height of triangle: "))
print("Area of triangle:", 0.5 * base * height)
Syntax used: float(), arithmetic operators, print()
Explanation: Calculates area of three geometric shapes using their standard formulas.
Expected output:
Radius of circle: 5
Area of circle: 78.5
Length of rectangle: 4
Breadth of rectangle: 6
Area of rectangle: 24.0
Base of triangle: 8
Height of triangle: 3
Area of triangle: 12.0
Practical 3: Gross Salary Calculation
bs = float(input("Enter Basic Salary: "))
da = 0.70 * bs
ta = 0.30 * bs
hra = 0.10 * bs
gross = bs + da + ta + hra
print("Basic Salary:", bs)
print("DA:", da)
print("TA:", ta)
print("HRA:", hra)
print("Gross Salary:", gross)
Syntax used: variables, percentage calculation, arithmetic operators
Explanation: Computes DA, TA, HRA based on basic salary and adds them to find gross salary.
Expected output:
Enter Basic Salary: 10000
Basic Salary: 10000.0
DA: 7000.0
TA: 3000.0
HRA: 1000.0
Gross Salary: 21000.0
Practical 4: Basic Arithmetic Operations
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Modulus:", a % b)
Syntax used: +, -, *, /, % operators
Explanation: Takes two numbers and performs all required arithmetic operations.
Expected output:
Enter first number: 10
Enter second number: 3
Addition: 13.0
Subtraction: 7.0
Multiplication: 30.0
Division: 3.3333333333333335
Modulus: 1.0
Practical 5: Task List Using List and Tuple
tasks = ["Study Python", "Write notes", "Solve practicals"]
# Add task
tasks.append("Revision")
# Update task
tasks[1] = "Write unit notes"
# Remove task
tasks.remove("Solve practicals")
# Sort tasks
tasks.sort()
# Convert to tuple
final_tasks = tuple(tasks)
print("Task List (Tuple):", final_tasks)
Syntax used: list methods append(), remove(), sort(), tuple()
Explanation: Demonstrates add, update, remove, sort operations using list and final storage in tuple.
Expected output:
Task List (Tuple): ('Revision', 'Study Python', 'Write unit notes')
Practical 6: Set Operations
python_students = {"Amit", "Riya", "Sana", "Jay"}
math_students = {"Riya", "Jay", "Neha"}
print("Union:", python_students | math_students)
print("Intersection:", python_students & math_students)
print("Difference (Python - Math):", python_students - math_students)
Syntax used: set literals {}, union |, intersection &, difference -
Explanation: Shows students in either class, both classes, and only Python class.
Expected output:
Union: {'Amit', 'Riya', 'Sana', 'Jay', 'Neha'}
Intersection: {'Riya', 'Jay'}
Difference (Python - Math): {'Amit', 'Sana'}
Practical 7: Student Dictionary Records
student = {
"name": "Anaya",
"grade": "A",
"attendance": 92
}
print("Original:", student)
# Update values
student["grade"] = "A+"
student["attendance"] = 95
print("Updated:", student)
Syntax used: dictionary key-value pairs, update using keys
Explanation: Creates student record and updates grade and attendance.
Expected output:
Original: {'name': 'Anaya', 'grade': 'A', 'attendance': 92}
Updated: {'name': 'Anaya', 'grade': 'A+', 'attendance': 95}
Practical 8: Even or Odd Using Conditions and Loop
for i in range(1, 6):
num = int(input(f"Enter number {i}: "))
if num % 2 == 0:
print(num, "is Even")
else:
print(num, "is Odd")
Syntax used: for loop, if-else, modulus operator
Explanation: Repeats input 5 times and checks each number as even or odd.
Expected output:
Enter number 1: 2
2 is Even
Enter number 2: 5
5 is Odd
Practical 9: Factorial of N
n = int(input("Enter a number: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print("Factorial =", fact)
Syntax used: loop with range(), multiplication assignment *=
Explanation: Multiplies numbers from 1 to n to find factorial.
Expected output:
Enter a number: 5
Factorial = 120
Practical 10: Prime Number Check Using Function
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
num = int(input("Enter number: "))
if is_prime(num):
print(num, "is Prime")
else:
print(num, "is Not Prime")
Syntax used: def, return, for loop, condition checking
Explanation: Function checks if number has any divisor other than 1 and itself.
Expected output:
Enter number: 7
7 is Prime
Practical 11: Calculator Using Functions
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Add:", add(a, b))
print("Sub:", sub(a, b))
print("Mul:", mul(a, b))
print("Div:", div(a, b))
Syntax used: function definition, function call, return
Explanation: Uses separate functions for each arithmetic operation to build a simple calculator.
Expected output:
Enter first number: 8
Enter second number: 2
Add: 10.0
Sub: 6.0
Mul: 16.0
Div: 4.0
Practical 12: Read File and Print Words of Given Length
filename = "sample.txt"
length = int(input("Enter word length to print: "))
with open(filename, "r") as f:
text = f.read()
words = text.split()
print("Words with length", length, ":")
for w in words:
if len(w) == length:
print(w)
Syntax used: with open(), read(), split(), len()
Explanation: Reads file content and prints only words matching user-specified length.
Expected output:
Enter word length to print: 5
Words with length 5:
apple
study
Practical 13: Create Executable File
# app.py
print("Hello, this is my executable Python app!")
# Command in terminal
# Install: pip install pyinstaller
# Build executable: pyinstaller --onefile app.py
Syntax used: terminal command, pyinstaller --onefile
Explanation: Write program in app.py, then use PyInstaller to generate .exe inside dist folder.
Expected output:
Hello, this is my executable Python app!
After running pyinstaller, an executable file is created in the dist folder.
Practical 14: Division with Exception Handling
try:
a = float(input("Enter numerator: "))
b = float(input("Enter denominator: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter valid numeric input.")
Syntax used: try, except ZeroDivisionError, except ValueError
Explanation: Handles two common runtime errors: zero division and invalid input.
Expected output:
Enter numerator: 10
Enter denominator: 2
Result: 5.0
Practical 15: Debugging with pdb
import pdb
num = int(input("Enter a number: "))
pdb.set_trace() # Breakpoint
square = num * num
print("Square:", square)
# Useful pdb commands inside debugger
# n -> next line
# p num -> print variable
# c -> continue program
Syntax used: import pdb, pdb.set_trace()
Explanation: Program pauses at breakpoint so you can inspect variables and step through execution.
Expected output:
Enter a number: 6
> ... pdb debugger starts here ...
Square: 36
Practical 16: Validate Phone and Email Using Regex
import re
phone = input("Enter phone (10 digits): ")
email = input("Enter email: ")
phone_pattern = r"^[6-9]\d{9}$"
email_pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"
print("Phone valid:", bool(re.match(phone_pattern, phone)))
print("Email valid:", bool(re.match(email_pattern, email)))
Syntax used: import re, re.match(), regex patterns
Explanation: Uses regular expressions to check valid phone format and email format.
Expected output:
Enter phone (10 digits): 9876543210
Enter email: test@gmail.com
Phone valid: True
Email valid: True
Practical 17: Extract Names, Emails, Phones Using Regex
import re
text = """
Asha 9876543210 asha@gmail.com
Rohan 9123456789 rohan@yahoo.com
"""
names = re.findall(r"[A-Z][a-z]+", text)
emails = re.findall(r"[\w\.-]+@[\w\.-]+\.\w+", text)
phones = re.findall(r"[6-9]\d{9}", text)
print("Names:", names)
print("Emails:", emails)
print("Phones:", phones)
Syntax used: re.findall(), character classes, quantifiers
Explanation: Extracts all matching names, emails, and phone numbers from text data.
Expected output:
Names: ['Asha', 'Rohan']
Emails: ['asha@gmail.com', 'rohan@yahoo.com']
Phones: ['9876543210', '9123456789']
Practical 18: Create 1D, 2D, 3D NumPy Arrays
import numpy as np
a1 = np.array([10, 20, 30, 40])
a2 = np.array([[1, 2], [3, 4]])
a3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("1D array:\n", a1)
print("2D array:\n", a2)
print("3D array:\n", a3)
print("Reshape 1D to 2x2:\n", a1.reshape(2, 2))
print("Slice 2D first row:", a2[0])
print("Index from 3D:", a3[1, 0, 1])
Syntax used: np.array(), reshape(), slicing, indexing
Explanation: Demonstrates NumPy array creation and basic operations like reshape, slice, and index access.
Expected output:
1D array:
[10 20 30 40]
2D array:
[[1 2]
[3 4]]
3D array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Reshape 1D to 2x2:
[[10 20]
[30 40]]
Slice 2D first row: [1 2]
Index from 3D: 6
Practical 19: Array Arithmetic, Dot Product, Cross Product
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Dot Product:", np.dot(a, b))
print("Cross Product:", np.cross(a, b))
Syntax used: vector operations, np.dot(), np.cross()
Explanation: Performs element-wise arithmetic and vector products on two NumPy arrays.
Expected output:
Addition: [5 7 9]
Subtraction: [-3 -3 -3]
Multiplication: [ 4 10 18]
Division: [0.25 0.4 0.5 ]
Dot Product: 32
Cross Product: [-3 6 -3]
Practical 20: Mean, Median, Standard Deviation, Variance, Correlation
import numpy as np
x = np.array([10, 20, 30, 40, 50])
y = np.array([12, 18, 33, 37, 52])
print("Mean:", np.mean(x))
print("Median:", np.median(x))
print("Standard Deviation:", np.std(x))
print("Variance:", np.var(x))
print("Correlation Coefficient:\n", np.corrcoef(x, y))
Syntax used: np.mean(), np.median(), np.std(), np.var(), np.corrcoef()
Explanation: Computes important statistical measures and correlation between two datasets.
Expected output:
Mean: 30.0
Median: 30.0
Standard Deviation: 14.142135623730951
Variance: 200.0
Correlation Coefficient:
[[1. 0.997...]
[0.997... 1. ]]