0% found this document useful (0 votes)
40 views

CS406 Python Lab April-2024

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

CS406 Python Lab April-2024

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Gyan Ganga College of Technology, Jabalpur

Department of Computer Science & Engineering

Lab Manual
CS406 Programming Practices
(c) Python

NAME:

ENROLLMENT NUMBER:

Faculty Incharge
Prof.Pankaj K.Jain/ Prof. Kamaljeet S.kalsi
CSE, GGCT
Session: 2023-24
List of Experiments

SIGN
CONDUCTION
S.NO AIM WITH GRADE(10)
DATE
DATE

1 Python Program to Make a Simple Calculator

Python program to find the factorial of a number


2
provided by the user

3 Python program to Demonstrate Star pattern.

4 Python program to check palindrome Number.

Write python programs to demonstrate LIST


5
python collection.

Write python programs to demonstrate TUPLE


6
python collection.

Python program to creates the instance of the


7
class and object

Python program to demonstrate the properties of


8
Inheritance

Python program to demonstrate the File Input /


9
Output operations

Python program to demonstrate the properties of


10
Date and Time
Aim-01-Python Program to Make a Simple Calculator

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()
Aim-02- Python program to find the factorial of a number provided by the user
# 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)
Aim-03- Python program to Demonstrate Star pattern

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)
Aim-04- Python program to check palindrome Number.

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")
Aim-05- write python programs to demonstrate TUPLE python collection.

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[:])
Aim-06- Write python programs to demonstrate LIST python collection.

 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[::])
Aim-07- Python program to creates the instance of the class and object

Python is an object oriented programming language. Almost everything in Python is an


object, with its properties and methods. A Class is like an object constructor, or a "blueprint"
for creating objects.
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"%(self.id,self.name))
# Creating a emp instance of Employee class
emp = Employee()
emp.display()
Aim-08- Python program to demonstrate the properties of Inheritance

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()
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')

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()

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()
obj1.info()
obj1.car_info('BMW')

obj2 = Truck()
obj2.info()
obj2.truck_info('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()

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()

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()
obj1.info()
obj1.car_info('BMW')

obj2 = Truck()
obj2.info()
obj2.truck_info('Ford')
Aim-09- Python program to demonstrate the File Input / Output operations

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 test.txt with the
following content.

# open file in current directory


file1 = open("test.txt")

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("test.txt", "r")

# read the file


read_content = file1.read()
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("test.txt", "r")

# read the file


read_content = file1.read()
print(read_content)

# close the file


file1.close()
Aim-10- Python program to demonstrate the properties of Date and Time

There are a number of ways we can take to get the current date. We will use the date class of
the date time module to accomplish this task.
The date time library provides necessary methods and functions to handle the following scenarios.

1. Date Time Representation


2. Date Time Arithmetic
3. Date Time Comparison

Python get today's date

from datetime import date

today = date.today()
print("Today's date:", today)

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 = datetime.now()

print("now =", now)

# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)

You might also like