LAB MANUAL
Subject: Programming Practices(Python)
Subject Code: CS406(C)
[Link] 4th Semester
COMPUTER SCIENCE &ENGINEERING
DEPARTMENT of COMPUTER SCIENCE
GYAN GANGA COLLEGE OF TECHNOLOGY
JABALPUR (M.P.)
Session: 2024- 2025
List of Experiments
S.N AIM DATE SIGN REMARKS
O
1 Python Program to Make a Simple Calculator
2 Python program to find the factorial of a number provided by the user
3 Write python programs to demonstrate TUPLE python collection.
4 Write python programs to demonstrate LIST python collection.
5 Python program to Demonstrate Star pattern
6 Python program to check palindrome Number
7 Python program to creates the instance of the class and object
8 Python program to demonstrate the properties of Inheritance
9 Python program to demonstrate the File Input/output operation
10 Python program to demonstrate the properties of Date and Time
11 Python program to implement conditional statements
12 Python program to implement iterative statements
13 Python program to implement Control statements
14 Python program to implement Exception Handling
15 Python program to implement User defined Exception
Experiment No. 1
Aim-Python Program to Make a Simple Calculator
Program-
def calculator():
while True:
# Print options for the user
print("Enter '+' to add two numbers")
print("Enter '-' to subtract two numbers")
print("Enter '*' to multiply two numbers")
print("Enter '/' to divide two numbers")
print("Enter 'quit' to end the program")
# Get user input
user_input = input(": ")
# Check if the user wants to quit
if user_input == "quit":
break
# Check if the user input is a valid operator
elif user_input in ["+", "-", "*", "/"]:
# Get first number
num1 = float(input("Enter a number: "))
# Get second number
num2 = float(input("Enter another number: "))
# Perform the operation based on the user input
if user_input == "+":
result = num1 + num2
print(num1, "+", num2, "=", result)
elif user_input == "-":
result = num1 - num2
print(num1, "-", num2, "=", result)
elif user_input == "*":
result = num1 * num2
print(num1, "*", num2, "=", result)
elif user_input == "/":
result = num1 / num2
print(num1, "/", num2, "=", result)
else:
# In case of invalid input
print("Invalid Input")
# Call the calculator function to start the program
calculator()
Output:
Enter '+' to add two numbers
Enter '-' to subtract two numbers
Enter '*' to multiply two numbers
Enter '/' to divide two numbers
Enter 'quit' to end the program
:
Experiment No. 2
Aim- Python program to find the factorial of a number provided by the user
Program-
# using recursion
def factorial(x):
if x == 1:
return 1
else:
# recursive call to the function
return (x * factorial(x-1))
# to take input from the user
num = int(input("Enter a number: "))
# call the factorial function
result = factorial(num)
print("The factorial of", num, "is", result)
Output:
Enter a number: 5
The factorial of 5 is 120
Experiment No. 3
Aim- write python programs to demonstrate TUPLE python collection.
Description & program:
There are four collection data types in the Python programming language:
List is a collection which is ordered and changeable. Allows duplicate members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
Dictionary is a collection which is ordered** and changeable. No duplicate members.
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the
other 3 are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
.
# Empty tuple
my_tuple = ()
print(my_tuple)
--------------------------------------------
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
--------------------------------------------
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
--------------------------------------------
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
--------------------------------------------
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
--------------------------------------------
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
--------------------------------------------
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
----------------------------------------------
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
--------------------------------------------------------------
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
--------------------------------------------
# accessing tuple elements using slicing
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
# elements 2nd to 4th index
print(my_tuple[1:4])
# elements beginning to 2nd
print(my_tuple[:-7]))
# elements 8th to end
print(my_tuple[7:])
# elements beginning to end
print(my_tuple[:])
Output:
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
banana
cherry
('cherry', 'orange', 'kiwi')
('apple', 'banana', 'cherry', 'orange')
Yes, 'apple' is in the fruits tuple
('r', 'o', 'g')
('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Experiment No. 4
Aim- write python programs to demonstrate LIST python collection.
Description & program:
A list in Python is used to store the sequence of various types of data.
A list can be defined as a collection of values or items of different types.
Python lists are mutable type which implies that we may modify its element after it
has been formed.
The items in the list are separated with the comma (,) and enclosed with the square
brackets [].
# a simple list
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
# printing the list
print(list1)
print(list2)
# printing the type of list
print(type(list1))
print(type(list2))
---------------------------
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
--------------------------------------------
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
----------------------------------------------
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
---------------------------------------------------
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
--------------------------------------------------
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
--------------------------
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
----------------------------------------------------------------
Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
-----------------------------------------------------------------
Change the second value by replacing it with two new values:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
-------------------------------------------------------------------
Change the second and third value by replacing it with one value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
-----------------------------------
Some more examples
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Show original list
print("\nOriginal List:\n", List)
print("\nSliced Lists: ")
# Display sliced list
print(List[3:9:2])
# Display sliced list
print(List[::2])
# Display sliced list
print(List[::])
Output:
[1, 2, 'Python', 'Program', 15.9]
['Amy', 'Ryan', 'Henry', 'Emma']
<class 'list'>
<class 'list'>
banana
cherry
cherry
['apple', 'banana', 'cherry', 'orange']
['cherry', 'orange', 'kiwi', 'melon', 'mango']
['apple', 'blackcurrant', 'cherry']
['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
['apple', 'blackcurrant', 'watermelon', 'cherry']
['apple', 'watermelon']
Original List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sliced Lists:
[4, 6, 8]
[1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Experiment No. 5
Aim- Python program to Demonstrate Star pattern
Program:
Patterns can be printed in python using simple for loops. First outer loop is used to
handle the number of rows and the Inner nested loop is used to handle the number of
columns. Manipulating the print statements, different number patterns, alphabet patterns, or
star patterns can be printed.
# Python 3.x code to demonstrate star pattern
# Function to demonstrate printing pattern
def pypart(n):
# outer loop to handle number of rows
# n in this case
for i in range(0, n):
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ",end="")
# ending line after each row
print("\r")
# Driver Code
n=5
pypart(n)
Output:
*
**
***
****
*****
Experiment No. 6
Aim- Python program to check palindrome Number.
Description & program:
A palindrome number (also known as a numeral palindrome or a numeric palindrome) is a
number (such as 16461) that remains the same when its digits are reversed.
Palindrome algorithm
Read the number or letter.
Hold the letter or number in a temporary variable.
Reverse the letter or number.
Compare the temporary variable with reverses letter or number.
If both letters or numbers are the same, print "this string/number is a palindrome."
Else print, "this string/number is not a palindrome."
num=int(input("enter number"))
print("num====", num)
num1=num
sum=0
while(num>0):
rem=num%10
sum=sum*10+rem
num=int(num/10)
print("sum==", sum)
if num1==sum:
print("number is palandrome")
else:
print("number is not palandrome")
Output:
enter number121
num==== 121
sum== 121
number is palandrome
Experiment No. 7
Aim- Python program to creates the instance of the class and object
Description & program:
A class needs to be instantiated if we want to use the class attributes in another class or
method. A class can be instantiated by calling the class using the class name.
class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%([Link],[Link]))
# Creating a emp instance of Employee class
emp = Employee()
[Link]()
Output:
ID: 10
Name: John
Experiment No. 8
Aim- Python program to demonstrate the properties of Inheritance
Description & program:
The process of inheriting the properties of the parent class into a child class is called
inheritance. The existing class is called a base class or parent class and the new class is
called a subclass or child class or derived class.
In Object-oriented programming, inheritance is an important aspect. The main purpose of
inheritance is the reusability of code because we can use the existing class to create a new
class instead of creating it from scratch.
In inheritance, the child class acquires all the data members, properties, and functions from
the parent class. Also, a child class can also provide its specific implementation to the
methods of the parent class.
The type of inheritance are listed below:
1. Single inheritance
2. Multiple Inheritance
3. Multilevel inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
For example, In the real world, Car is a sub-class of a Vehicle class. We can create a Car by
inheriting the properties of a Vehicle such as Wheels, Colors, Fuel tank, engine, and add
extra properties in Car as required.
Single Inheritance
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Create object of Car
car = Car()
# access Vehicle's info using car object
car.Vehicle_info()
car.car_info()
Output:
Inside Vehicle class
Inside Car class
Multiple Inheritance
# Parent class 1
class Person:
def person_info(self, name, age):
print('Inside Person class')
print('Name:', name, 'Age:', age)
# Parent class 2
class Company:
def company_info(self, company_name, location):
print('Inside Company class')
print('Name:', company_name, 'location:', location)
# Child class
class Employee(Person, Company):
def Employee_info(self, salary, skill):
print('Inside Employee class')
print('Salary:', salary, 'Skill:', skill)
# Create object of Employee
emp = Employee()
# access data
emp.person_info('Jessa', 28)
emp.company_info('Google', 'Atlanta')
emp.Employee_info(12000, 'Machine Learning')
Output:
Inside Person class
Name: Jessa Age: 28
Inside Company class
Name: Google location: Atlanta
Inside Employee class
Salary: 12000 Skill: Machine Learning
Multilevel inheritance
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Child class
class SportsCar(Car):
def sports_car_info(self):
print('Inside SportsCar class')
# Create object of SportsCar
s_car = SportsCar()
# access Vehicle's and Car info using SportsCar object
s_car.Vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Output:
Inside Vehicle class
Inside Car class
Inside SportsCar class
Hierarchical Inheritance
class Vehicle:
def info(self):
print("This is Vehicle")
class Car(Vehicle):
def car_info(self, name):
print("Car name is:", name)
class Truck(Vehicle):
def truck_info(self, name):
print("Truck name is:", name)
obj1 = Car()
[Link]()
obj1.car_info('BMW')
obj2 = Truck()
[Link]()
obj2.truck_info('Ford')
Output:
This is Vehicle
Car name is: BMW
This is Vehicle
Truck name is: Ford
Hybrid Inheritance
class Vehicle:
def vehicle_info(self):
print("Inside Vehicle class")
class Car(Vehicle):
def car_info(self):
print("Inside Car class")
class Truck(Vehicle):
def truck_info(self):
print("Inside Truck class")
# Sports Car can inherits properties of Vehicle and Car
class SportsCar(Car, Vehicle):
def sports_car_info(self):
print("Inside SportsCar class")
# create object
s_car = SportsCar()
s_car.vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Output:
Inside Vehicle class
Inside Car class
Inside SportsCar class
Multilevel inheritance
In multilevel inheritance, a class inherits from a child class or derived class. Suppose three
classes A, B, C. A is the superclass, B is the child class of A, C is the child class of B. In
other words, we can say a chain of classes is called multilevel inheritance.
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Child class
class SportsCar(Car):
def sports_car_info(self):
print('Inside SportsCar class')
# Create object of SportsCar
s_car = SportsCar()
# access Vehicle's and Car info using SportsCar object
s_car.Vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Output:
Inside Vehicle class
Inside Car class
Inside SportsCar class
Hierarchical Inheritance
In Hierarchical inheritance, more than one child class is derived from a single parent class. In
other words, we can say one parent class and multiple child classes.
class Vehicle:
def info(self):
print("This is Vehicle")
class Car(Vehicle):
def car_info(self, name):
print("Car name is:", name)
class Truck(Vehicle):
def truck_info(self, name):
print("Truck name is:", name)
obj1 = Car()
[Link]()
obj1.car_info('BMW')
obj2 = Truck()
[Link]()
obj2.truck_info('Ford')
Output:
This is Vehicle
Car name is: BMW
This is Vehicle
Truck name is: Ford
Experiment No. 9
Aim- Python program to demonstrate the File Input/ Output operations
Description & program:
A file is a container in computer storage devices used for storing data.
When we want to read from or write to a file, we need to open it first. When we are done, it
needs to be closed so that the resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
Open a file
Read or write (perform operation)
Close the file
Opening Files in Python
In Python, we use the open() method to open files.
To demonstrate how we open files in Python, let's suppose we have a file named [Link] with
the following content.
# open file in current directory
file1 = open("[Link]")
Reading Files in Python
After we open a file, we use the read() method to read its contents. For example,
# open a file
file1 = open("[Link]", "r")
# read the file
read_content = [Link]()
print(read_content)
Closing Files in Python
When we are done with performing operations on the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file. It is done using
the close() method in Python. For example,
# open a file
file1 = open("[Link]", "r")
# read the file
read_content = [Link]()
print(read_content)
# close the file
[Link]()
Experiment No. 10
Aim- Python program to demonstrate the properties of Date and Time
Description & program:
There are a number of ways we can take to get the current date. We will use the date class of
the datetime module to accomplish this task.
Python get today's date
from datetime import date
today = [Link]()
print("Today's date:", today)
output:
Today's date: 2025-05-07
Get the current date and time in Python
If we need to get the current date and time, you can use the datetime class of
the datetime module.
from datetime import datetime
# datetime object containing current date and time
now = [Link]()
print("now =", now)
# dd/mm/YY H:M:S
dt_string = [Link]("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)
Output:
now = 2025-05-07 09:32:47.279540
date and time = 07/05/2025 09:32:47
Experiment No. 11
Aim- Python program to implement conditional statements
Description & program:
Conditional statements in Python are used to execute certain blocks of code based on specific
conditions. These statements help control the flow of a program, making it behave differently
in different situations.
If Conditional Statement in Python
If statement is the simplest form of a conditional statement. It executes a block of code if the
given condition is true.
1. Example:
age = 20
if age >= 18:
print("Eligible to vote.")
Output
Eligible to vote.
Short Hand if
Short-hand if statement allows us to write a single-line if statement.
2. Example:
age = 19
if age > 18: print("Eligible to Vote.")
Output
Eligible to Vote.
3. Example:
age = 10
if age <= 12:
print("Travel for free.")
else:
print("Pay for ticket.")
Output
Travel for free.
Short Hand if-else
4. Example:
marks = 45
res = "Pass" if marks >= 40 else "Fail"
print(f"Result: {res}")
Output:
Result: Pass
5. Example:
age = 25
if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")
Output:
Young adult.
6. Example:
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")
Output:
30% senior discount!
Experiment No. 12
Aim- Python program to implement iterative statements
Program:
Python While Loop Syntax:
while expression:
statement(s)
Example of Python While Loop:
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Python")
Output
Hello Python
Hello Python
Hello Python
Syntax of While Loop with else statement:
while condition:
# execute these statements
else:
# execute these statements
Example:
The code prints “Hello Geek” three times using a ‘while’ loop and then after the loop it prints “In Else
Block” because there is an “else” block associated with the ‘while’ loop.
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Python")
else:
print("In Else Block")
Output
Hello Python
Hello Python
Hello Python
In Else Block
Infinite While Loop in Python
count = 0
while (count == 0):
print("Hello python")
For Loop in Python
For Loop Syntax:
for iterator_var in sequence:
statements(s)
n=4
for i in range(0, n):
print(i)
Output:
0
1
2
3
Experiment No. 13
Aim- Python program to implement Control statements
Description & program:
Control statements modify the loop’s execution flow. Python provides three primary control
statements: continue, break, and pass.
break Statement
The break statement is used to exit the loop prematurely when a certain condition is met.
# Using break to exit the loop
for i in range(10):
if i == 5:
break
print(i)
Output
0
1
2
3
4
Continue Statement
The continue statement skips the current iteration and proceeds to the next iteration of the loop.
# Using continue to skip an iteration
for i in range(10):
if i % 2 == 0:
continue
print(i)
Output
1
3
5
7
9
Pass Statement
The pass statement is a null operation; it does nothing when executed. It’s useful as a placeholder
for code that you plan to write in the future.
# Using pass as a placeholder
for i in range(5):
if i == 3:
pass
print(i)
Output:
0
1
2
3
4
Experiment No. 14
Aim- Python program to implement Exception Handling
Description & program:
Python Exception Handling handles errors that occur during the execution of a program.
Exception handling allows to respond to the error, instead of crashing the running program.
# Example
n = 10
try:
res = n / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Can't be divided by zero!")
Output
Can't be divided by zero!
Syntax and Usage
Exception handling in Python is done using the try, except, else and finally blocks.
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs
Example:
try:
n=0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")
Output:
You can't divide by zero!
Execution complete.
Experiment No. 15
Aim- Python program to implement User defined Exception
Description & program:
In Python, exceptions are used to handle errors that occur during the execution of a program.
While Python provides many built-in exceptions, sometimes we may need to create our own
exceptions to handle specific situations that are unique to application. These are called user-defined
exceptions.
Steps to Create and Use User-Defined Exceptions
Define a New Exception Class: Create a new class that inherits from Exception or any of its
subclasses.
Raise the Exception: Use the raise statement to raise the user-defined exception when a specific
condition occurs.
Handle the Exception: Use try-except blocks to handle the user-defined exception.
Example of a User-Defined Exception:
# Step 1: Define a custom exception class
class InvalidAgeError(Exception):
def __init__(self, age, msg="Age must be between 0 and 120"):
[Link] = age
[Link] = msg
super().__init__([Link])
def __str__(self):
return f'{[Link]} -> {[Link]}'
# Step 2: Use the custom exception in your code
def set_age(age):
if age < 0 or age > 120:
raise InvalidAgeError(age)
else:
print(f"Age set to: {age}")
# Step 3: Handling the custom exception
try:
set_age(150) # This will raise the custom exception
except InvalidAgeError as e:
print(e)
Output
150 -> Age must be between 0 and 120