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

Pp Lab Manual

Uploaded by

haseebsyed8910
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Pp Lab Manual

Uploaded by

haseebsyed8910
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

1. Introduction to Python Lab: Installation and Simple Output Display.

a) Write a python program to read a string “Python Programming” and display it on the screen.
b) Write a python program to read integer, float & string values and display them on the screen
c) Write a python program to display students details like name, htno, phno on screen.

a) Write a python program to read a string “Python Programming” and display it on the screen.

# Define the string


string = "Python Programming"
# Display the string on the screen
print(string)

Output

Python Programming

b) Write a python program to read integer, float & string values and display them on the screen

# Read an integer value


x = int(input("Enter an integer: "))
# Read a float value
y = float(input("Enter a float: "))
# Read a string value
str = input("Enter a string: ")
# Display the values on the screen
print("\nYou entered:")
print("Integer:", x)
print("Float:", y)
print("String:", str)

Output:
Enter an integer: 10
Enter a float: 3.14
Enter a string: Hello, Python!
You entered:
Integer: 10
Float: 3.14
String: Hello, Python!
c) Write a program to display students details like name,htno,phno, address on screen.

name="sameer"
htno=160924777001
phno=999999999
address="h-no: 8-22-1, Tolichowki, Hyderabad "
print("name=",name)
print("htmo",htno)
print("phno=",phno)
print("Addrees=",address)

Output:
name= sameer
htmo 160924777001
phno= 999999999
Addrees= h-no: 8-22-1, Tolichowki, Hyderabad
2. Programs using Input Output Statements, Variables and Expressions.
a) Write a python program to read a float value and convert Fahrenheit to Centigrade.
b) Write a python program to find the area of triangle.
c) Write a python program to read the marks in four subjects and display the average.
d) write a python program to find simple interest.

a)Write a python program to read a float value and convert Fahrenheit to Centigrade.

temperature = float(input("Please enter temperature in fahrenheit:"))


celsius = (temperature - 32) * 5 / 9
print("Temperature in celsius: " , celsius)

Output:
Please enter temperature in fahrenheit:44
Temperature in celsius: 6.666666666666667

b) Write a python program to find the area of triangle.

# Read the base and height of the triangle


base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))

# Calculate the area of the triangle


area = 0.5 * base * height

# Display the area of the triangle


print("The area of the triangle is: ",area)

Output:
Enter the base of the triangle: 10
Enter the height of the triangle: 11
The area of the triangle is: 55.0
c)Write a python program to read the marks in four subjects and display the average.

# Read the marks for four subjects


mark1 = float(input("Enter marks for Subject 1: "))
mark2 = float(input("Enter marks for Subject 2: "))
mark3 = float(input("Enter marks for Subject 3: "))
mark4 = float(input("Enter marks for Subject 4: "))

# Calculate the average of the marks


average = (mark1 + mark2 + mark3 + mark4) / 4

# Display the average


print("The average of the marks is: ",average)

Output:
Enter marks for Subject 1: 60
Enter marks for Subject 2: 76
Enter marks for Subject 3: 89
Enter marks for Subject 4: 56
The average of the marks is: 70.25

d)Write a python program to find simple interest

p=int(input("Enter principle amount:"))


t=int(input("Enter time in months:"))
r=int(input("Enter rate of intrest:"))

si=p*t*r/100

print("simple intrest=",si)

Output:

Enter principle amount:10000


Enter time in months:12
Enter rate of intrest:2
simple intrest= 2400.0
3. Programs using various operators in Python.
a) Write a python program for demonstrating the usage of comparison operators
b) Write a python program for demonstrating identity and membership operators.
c) Write a python program for demonstrating the usage of bitwise operators.
d) Write a python program for demonstrating the usage of arithmetic operators

a) Write a python program for demonstrating the usage of comparison operators

# Variables for comparison

a =15
b =20
# equal to operator
print("a == b is", a == b)
# not equal to operator
print("a != b is", a != b)
# greater than operator
print("a > b is", a > b)
# less than operator
print("a < b is", a < b)
# greater than or equal to operator
print("a >= b is ", a >= b)
# less than or equal to operator
print("a <= b is", a <= b)

Output:
a == b is False
a != b is True
a > b is False
a < b is True
a >= b is False
a <= b is True

b) Write a python program for demonstrating identity and membership operators.


x=[1,2,3]
y=[1,2,3]
z=x
#identity operators
print( x is z)
print(y is z)
print(x is y)
print("----------")
print( x is not z)
print(y is not z)
print(x is not y)
print("----------")
#membership operators

s = ["apple", "banana","orange"]

print("banana" in s)
print("orange" not in s)
print("----------")
my_list = [2, 4, 6, 8, 10, 12]
print(6 in my_list)
print(5 not in my_list)

output:
True
False
False
----------
False
True
True
----------
True
False
----------
True
True

c) Write a python program for demonstrating the usage of bitwise operators.

a = 10
b=4
print("a & b =", a & b)
print("a | b =", a | b)
print("a ^ b =", a ^ b)
print("~a =", ~a)
print("a >> 1 =", a >> 1)
print("b << 1 =", b << 1)

Output:
a&b=0
a | b = 14
a ^ b = 14
~a = -11
a >> 1 = 5
b << 1 = 8
d)Write a python program to demonstrating the usage of arithmetic operators

a = int(input("Enter first number:"))


b = int(input("Enter second number:"))

# addition
print ('Sum: ', a + b)

# subtraction
print ('Subtraction: ', a - b)

# multiplication
print ('Multiplication: ', a * b)

# division
print ('Division: ', a / b)

# floor division
print ('Floor Division: ', a // b)

# modulo
print ('Modulo: ', a % b)

# a to the power b
print ('Power: ', a ** b)

output:

Enter first number:10


Enter second number:2
Sum: 12
Subtraction: 8
Multiplication: 20
Division: 5.0
Floor Division: 5
Modulo: 0
Power: 100
4. Programs using conditional statements
a) Write a python program to print a number is positive/negative using if-else.
b) Write a python program to find the largest number among three numbers.
c) Write a python program to swap two variables.
d) Write a python to calculate the electricity bill consumed by the user.
e) Write a python program to check whether a given number is even or odd.

a) Write a python program to print a number is positive/negative using if-else.

num = int(input("Enter a number: "))


if num > 0:
print("Positive number")
elif num = = 0:
print("Zero")
else:
print("Negative number")

Output:

Enter a number: 23
Positive number

b) Write a python program to find the largest number among three numbers.

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

Output:
Enter first number: 34
Enter second number: 55
Enter third number: 67
The largest number is 67.0
c) Write a python program to swap two variables.

#Method1: without using temporary variable

a = input('Enter value of a: ')


b = input('Enter value of b: ')

print("values before swapping")


print("a=",a)
print("b=",b)

a, b = b, a

print("values after swapping")


print("a=",a)
print("b=",b)
----------------------------------------

#Method2:with using temporary variable

a = input('Enter value of a: ')


b = input('Enter value of b: ')

print("values before swapping")


print("a=",a)
print("b=",b)
# create a temporary variable and swap the values
temp = a
a=b
b= temp
print("values after swapping")
print("a=",a)
print("b=",b)

output:
Enter value of a: 12
Enter value of b: 32
values before swaping
a= 12
b= 32
values after swaping
a= 32
b= 12
d) Write a python to calculate the electricity bill consumed by the user.

cust_id=int(input("Input Customer ID :"))


cust_name = input("Input the name of the customer :")
unit_consumed=int(input("Input the unit consumed by the customer : "))

if(unit_consumed<200):
charge=1.20
elif(unit_consumed>=200 and unit_consumed<400):
charge=1.50
elif(unit_consumed>=400 and unit_consumed<600):
charge=1.80
else:
charge=2.00

gramt = unit_consumed*charge

if(gramt>300):
sur_charge=gramt*15/100.0
else:
sur_charge=gramt*10/100.0

net_amt = gramt+sur_charge
if(net_amt<100):
net_amt=100
print("ELECTRICITY BILL")
print("Customer Id Number : ", cust_id)
print("Customer Name : ", cust_name)
print("Unit Consumed : ", unit_consumed)
print("Amount Charges @Rs.",charge," per unit : ",gramt)
print("Surcharge Amount : ", sur_charge)
print("Net Amount Paid By the Customer : ", net_amt)

Output:
Input Customer ID :1
Input the name of the customer :XYZ
Input the unit consumed by the customer : 200
ELECTRICITY BILL
Customer Id Number : 1
Customer Name : XYZ
Unit Consumed : 200
Amount Charges @Rs. 1.5 per unit : 300.0
Surcharge Amount : 30.0
Net Amount Paid By the Customer : 330.0
d) Write a python program to Write a python program to to check whether given number is even or
odd.

num = int(input("Enter a number: "))

if (num %2 ) ==0:
print("Given number is EVEN")
else:
print("Given number is ODD

Output 1 :

Enter a number: 4
Given number is EVEN

OutPut 2:

Enter a number: 9
Given number is ODD
5. Programs using iterative statements
a) Write a python program to reverse the digits of a given number.
b) Write a python program to find the factorial of a given number
c) Write python Program to print all Prime numbers in an Interval
d) Write a python program to print the Fibonacci series up to n numbers
e) Write a python program to print all even numbers in an Interval
f) Write a python program to print number triangle.

a) Write a python program to reverse the digits of a given number.

number = int(input("Enter the integer number: "))

revs_number = 0

while (number > 0):


remainder = number % 10
revs_number = (revs_number * 10) + remainder
number = number // 10

print("The reverse number is :",revs_number)


Output:
Enter the integer number: 123
The reverse number is : 321

b) Write a python program to find the factorial of a given number

num = int(input("Enter a number: "))


factorial = 1
if num < 0:
print(" Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output:
Enter a number: 3
The factorial of 3 is 6
c) Write python Program to print all Prime numbers in an Interval

lower_value = int(input ("Please, Enter the Lowest Range Value: "))


upper_value = int(input ("Please, Enter the Upper Range Value: "))

print ("The Prime Numbers in the range are: ")


for number in range (lower_value, upper_value + 1):
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:
print (number)

Output:
Please, Enter the Lowest Range Value: 5
Please, Enter the Upper Range Value: 21
The Prime Numbers in the range are:
5
7
11
13
17
19

d) Write a python program to print the Fibonacci series up to n numbers

n = int(input ("Enter the number you want to print: "))

a=0
b=1
print("fibonacci series is:")
for i in range(0,n):
print(a, end = " ")
c = a+b
a=b
b=c
Output:
Enter the number you want to print: 5
fibonacci series is:
01123
e) Write a python program to Write a python program to print all even numbers in an Interval

# Input for the range

start = int(input("Enter the start of the interval: "))


end = int(input("Enter the end of the interval: "))

# Loop through the interval

for num in range(start, end + 1):


if num % 2 == 0:
print(num)

Output:

Enter the start of the interval: 6


Enter the end of the interval: 20
6
8
10
12
14
16
18
20

f) Write a python program to print number triangle.

# Input the number of rows for the triangle

n = int(input("Enter the number of rows: "))

# Loop to print the number triangle


for i in range(1, n + 1):

for j in range(1, i + 1):


print(j, end=" ")
print() # Move to the next line after each row

Output:
Enter the number of rows: 6
1
12
123
1234
12345
123456
6. Programs using strings
a) Write a python program that asks the user to enter a string and perform the following:
i) The total number of characters in the string.
ii) Repeat the string 10 times.
iii) The first character of the string.
iv) The first three characters of the string
b) Write a python program to check whether the given string is palindrome or not.
c). Write a program to create, concatenate, and print a string and access a substring from a given string.
d). Write a program to print the given string in reverse order.

a) Write a python program that asks the user to enter a string and perform the following:
i) The total number of characters in the string.
ii) Repeat the string 10 times.
iii) The first character of the string.
iv) The first three characters of the string

string = "Python program on string ";


count = 0;

#Counts each character except space


for i in range(0, len(string)):
if(string[i] != ' '):
count = count + 1;

print("Total number of characters in a string: " + str(count));


print(" repeat string for 10 times")
print(string*10)
print("first character of string=",string[0])
print("first 3 characters of string=",string[:3])

Output:

Total number of characters in a string: 21


repeat string for 10 times
Python program on string Python program on string Python program on string Python program on
string Python program on string Python program on string Python program on string Python program
on string Python program on string Python program on string
first character of srting= P
first 3 characters of string= Pyt

b) Write a python program to check whether the given string is palindrome or not.
#code
s = "malayalam"
ans = s[::-1]
if ans==s:
print("Yes it is palindrome")
else:
print("No, it is not palindrome")

Output:
Yes it is palindrome
c). Write a program to create, concatenate, and print a string and access a substring from a given
string.

# Defining strings
str1 = "Welcome to"
str2 = "Python Programming Lab "

# + Operator is used to strings concatenation


str3 = str1 + str2
print("The new concatenated string is " + str3) # Printing the new combined string

str4 = "abc"

# printing original string


print("The original string is : " + str4)

# Get all substrings of string


# Using list comprehension + string slicing

res = [str4[i: j] for i in range(len(str4))


for j in range(i + 1, len(str4) + 1)]

# printing result
print("All substrings of string are : " + str(res))
Output:

The new concatenated string is Welcome toPython Programming Lab


The original string is : abc
All substrings of string are : ['a', 'ab', 'abc', 'b', 'bc', 'c']

d) Write a python program to the given string in reverse order.

# Input the string from the user


string = input("Enter a string: ")

# Reverse the string using slicing


reversed_string = string[::-1]

# Output the reversed string


print("Reversed string:", reversed_string)

Output:

Enter a string: python programming

Reversed string: gnimmargorp nohtyp


7. Program on user-defined functions:
a)Write a python program to demonstrate how to pass parameters to a function.
b) Write a python program to demonstrate arguments in a function
c) Write a program to illustrate the scope of a variable inside a function.
d) Write a python program to find the factorial of a given number using a function.
e) Write a python program to find the factorial of a given number using the Recursive function.

a)Write a python program to demonstrate how to pass parameters to a function.

# Declaring a function
def my_function(fname, lname):
print(fname + " " + lname)
# Calling function
my_function("Albert", "Einstein")

Output:
Albert Einstein

b) Write a python program to demonstrate arguments in a function

print("Argument Example")
# Declaring a function
def my_function(fname):
print(fname + " khan")
# Calling function
my_function("Saba")
my_function("Salman")
my_function("Zohran")
Output:
Argument Example
Saba khan
Salman khan
Zohran khan

c) Write a program to illustrate the scope of a variable inside a function.

def my_func():
# local scope
x = 10
print("Value inside function:",x)

# Global scope
x = 20
my_func()
print("Value outside function:",x)

Output:
Value inside function: 10
Value outside function: 20
d) Write a python program to find the factorial of a given number using a function

def factorial(x):
"""This is a non recursive function
to find the factorial of an integer"""
factorial = 1
if num < 0:
print(" Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

num = int(input("Enter a number"))


factorial(num)

Output:
Enter a number5
The factorial of 5 is 120

e) Write a python program to find the factorial of a given number using the Recursive function

def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))

num = int(input("Enter a number"))


print("The factorial of", num, "is", factorial(num))

Output:
Enter a number 5
The factorial of 5 is 120
8. Program on lambda functions
a) Write a program to double a given number and add two numbers using lambda()
b) Write a program for filter () to filter only even numbers from a given list.
c) Write a Python Program to Make a Simple Calculator.
d) Write a program to perform basic operations on the random module

a) Write a program to double a given number and add two numbers using lambda()

#code to double a given number


double = lambda x: x * 2
print(double(5))

#code to add two numbers


x = lambda a, b : a + b
print(x(5, 6))

Output:
10
11

b) Write a program for filter () to filter only even numbers from a given list

# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Lambda function to check if a number is even


is_even = lambda x: x % 2 == 0

# Use filter to get even numbers


even_numbers = list(filter(is_even, numbers))

print("Even numbers in the list:", even_numbers)

Output:
Even numbers in the list: [2, 4, 6, 8, 10]
c) Write a Python Program to Make a Simple Calculator.

# This function adds two numbers


def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

# Take input from the user


choice = input("Enter choice(1/2/3/4): ")
# Check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid Input")

Output:

Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 1
Enter first number: 6
Enter second number: 9
6.0 + 9.0 = 15.0
d) Write a program to perform basic operations on the random module

import random
num = random.randrange(1, 10)
print( num )
num = random.randrange(1, 10, 2)
print( num )
num = random.randrange(0, 101, 10)
print( num )

Output: Note* : Each time output will be different


4
9
20

2.Explanation – Select Random Elements

#code
import random
random_s = random.choice('Random Module') #a string
print( random_s )
random_l = random.choice([23, 54, 765, 23, 45, 45]) #a list
print( random_l )
random_s = random.choice((12, 64, 23, 54, 34)) #a set
print( random_s )

Output: Note* : Each time output will be different


M
765
54

Explanation –Shuffle Elements Randomly

#code
import random
a_list = [34, 23, 65, 86, 23, 43]
random.shuffle( a_list )
print( a_list )
random.shuffle( a_list )
print( a_list )

Output: Note* : Each time output will be different


[43, 23, 34, 86, 65, 23]
[65, 43, 86, 34, 23, 23]
9. Program on data structure
a) Create a list and perform the following methods
1) Insert() 2) remove() 3) append() 4) len() 5) pop() 6)clear()
b) Create a dictionary and apply the following methods
1) Print the dictionary items 2) access items 3) useget () 4) change values 5) use len()
c) Create a tuple and perform the following methods
1) Add items 2) len() 3) check for item in tuple 4)Access items

a) Create a list and perform the following methods


1) Insert() 2) remove() 3) append() 4) len() 5) pop() 6)clear()

print("Create a list")
mylist = ["apple", "banana", "cherry"]
print(mylist)

print("Add an item at a specified index")


mylist = ["apple", "banana", "cherry"]
mylist.insert(1, "orange")
print(mylist)

print("Get the length of a list")


mylist = ["apple", "banana", "cherry"]
print(len(mylist))

print("Add an item to the end of the a list")


mylist = ["apple", "banana", "cherry"]
mylist.append("orange")
print(mylist)

print("Remove an item")
mylist = ["apple", "banana", "cherry"]
mylist.remove("banana")
print(mylist)

print("Remove the last item")


mylist = ["apple", "banana", "cherry"]
mylist.pop()
print(mylist)

print("Remove an item at a specified index")


mylist = ["apple", "banana", "cherry"]
del mylist[0]
print(mylist)

print("Empty list")
mylist = ["apple", "banana", "cherry"]
mylist.clear()
print(mylist)
output:

create a list
['apple', 'banana', 'cherry']
Add an item at a specified index
['apple', 'orange', 'banana', 'cherry']
Get the length of a list
3
Add an item to the end of the a list
['apple', 'banana', 'cherry', 'orange']
Remove an item
['apple', 'cherry']
Remove the last item
['apple', 'banana']
Remove an item at a specified index
['banana', 'cherry']
Empty list
[]

b) Create a dictionary and apply the following methods


1) Print the dictionary items 2) access items 3) useget () 4) change values 5) use len()

print("1.Create and print a dictionary:")


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

print(" 2. Accessing Items:”)


# Get the value of the "model" key:
x = thisdict["model"]
print(x)

print("3. Using get() Method:")


#There is also a method called get() that will give you the same result:
print("Get the value of the model key:")
x = thisdict.get("model")
print(x)

print("4. Change values:")


#Change the "year" to 2022:
thisdict["year"] = 2022
print(thisdict)

print("5.Print the number of items in the dictionary:")


print(len(thisdict))
Output:

1.Create and print a dictionary:


{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
2. Accessing Items:
Mustang
3. Using get() Method:
Get the value of the model key:
Mustang
4. Change values:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2022}
5.Print the number of items in the dictionary:
3

c) Create a tuple and perform the following methods


1) Add items 2) len() 3) check for item in tuple 4)Access items

print("1. Create a tuple")


thistuple = ("apple", "banana", "cherry")
print(thistuple)

print(“2.Add Items”)
#Convert the tuple into a list, add "orange", and convert it back into a tuple:
y = list(thistuple)
y.append("orange")

thistuple = tuple(y)
print(thistuple)

print("3.Check if a tuple item exists")


if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

print("4.Access tuple items")


print(thistuple[1])

print("Loop through a tuple")


for x in thistuple:
print(x)

print("5.Get the length of a tuple ")


print(len(thistuple))
Output:

1. Create a tuple
('apple', 'banana', 'cherry')
2.Add Items
('apple', 'banana', 'cherry', 'orange')
3.Check if a tuple item exists
Yes, 'apple' is in the fruits tuple
4.Access tuple items
banana
Loop through a tuple
apple
banana
cherry
orange
5.Get the length of a tuple
4

10.Program on OOPs concepts


a) Write a Python program to call data members and function using classes and objects
b) Write a python program to create a class representing a shopping cart. Include methods for adding
and removing items and calculate the total price.
c) Write a Python program to demonstrate inheritance
d) Write a Python program to demonstrate polymorphism
e) Write a Demonstrate a python code to print try, except and finally block statements

a) Write a Python program to call data members and function using classes and objects

#defining a class
class Room:
#data members
length = 0.0
breadth = 0.0

# method to calculate area


def calculate_area(self):
print("Area of Room =",self. length * self.breadth)

# create object of Room class


room1 = Room()

# assign values to data members


room1.length = 42.5
room1.breadth = 30.8

# access method of the Room class


room1.calculate_area()

Output:
Area of Room = 1309.0
b) Write a python program to create a class representing a shopping cart. Include methods for adding
and removing items and calculate the total price.

# Define a class called ShoppingCart to represent a shopping cart


class ShoppingCart:

# Initialize the shopping cart with an empty list of items


def __init__(self):
self.items = []

# Add an item with a name and quantity to the shopping cart


def add_item(self, item_name, qty):
item = (item_name, qty)
self.items.append(item)

# Remove an item with a specific name from the shopping cart


def remove_item(self, item_name):
for item in self.items:
if item[0] == item_name:
self.items.remove(item)
break

# Calculate and return the total quantity of items in the shopping cart
def calculate_total(self):
total = 0
for item in self.items:
total += item[1]
return total

# Example usage
# Create an instance of the ShoppingCart class
cart = ShoppingCart()

# Add items to the shopping cart


cart.add_item("Papaya", 100)
cart.add_item("Guava", 200)
cart.add_item("Orange", 150)

# Display the current items in the cart and calculate the total quantity
print("Current Items in Cart:")
for item in cart.items:
print(item[0], "-", item[1])

total_qty = cart.calculate_total()
print("Total Quantity:", total_qty)

# Remove an item from the cart, display the updated items, and recalculate the total quantity
cart.remove_item("Orange")
print("\nUpdated Items in Cart after removing Orange:")
for item in cart.items:
print(item[0], "-", item[1])
total_qty = cart.calculate_total()
print("Total Quantity:", total_qty)

output:

Current Items in Cart:


Papaya - 100
Guava - 200
Orange - 150
Total Quantity: 450

Updated Items in Cart after removing Orange:


Papaya - 100
Guava - 200
Total Quantity: 300

c) Write a Python program to demonstrate inheritance

#Inheritance Concept using the Quadrilateral


class quadriLateral:
def __init__(self, a, b, c, d):
self.side1=a
self.side2=b
self.side3=c
self.side4=d
def perimeter(self):
p=self.side1 + self.side2 + self.side3 + self.side4
print("perimeter=",p)

q1=quadriLateral(7,5,6,4)
q1.perimeter()

class rectangle(quadriLateral):
def __init__(self, a, b):
super().__init__(a, b, a, b)
r1=rectangle(10, 20)
r1.perimeter()

Output:

perimeter= 22
perimeter= 60
d) Write a Python program to demonstrate polymorphism

#The following program demonstrates method overriding in action:


class A:
def explore(self):
print("explore() method from class A")

class B(A):
def explore(self):
print("explore() method from class B")

b_obj =B()
a_obj =A()

b_obj.explore()
a_obj.explore()

Output:

explore() method from class B


explore() method from class A

e) Demonstrate a python code to print try, except and finally block statements

try:
thislist = ["apple", "banana", "cherry"]
thislist.remove("orange")
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
print(thislist)

Output:

Something went wrong


The 'try except' is finished
['apple', 'banana', 'cherry']
11. Programs on files
a) Write a python program to open and write “hello world” into a file and check the access
permissions to that file?
b) Write a Python code to merge two given file contents into a third file
c) Write a function that reads a file file1 and displays the number of words, number of vowels, blank
spaces,lower case letters and uppercase letters

a) Write a python program to open and write “hello world” into a file and check the access
permissions to that file?

#Create a new file


f = open("PPLab.txt", "w")

#Write to an Existing File


#Open the file “PPLab.txt", and append content to the file:
f = open("PPLab.txt", "a")

f.write("Hello World ! the file has more content!")


f.close()

#open and read the file after the appending:


f = open("PPLab.txt", "r")
print(f.read())
f = open("PPLab.txt", "r")

#stores all the data of the file into the variable content
content = f.read(4)

# prints the type of the data stored in the file


print(type(content))

#prints the content of the file


print(content)

# Close file
f = open("PPLab.txt ", "r")
print(f.readline())
f.close()

# x: it creates a new file with the specified name. It causes an error a file exists with the same name.
f1 = open("PPLab.txt","x")
print(f1)
if f1:
print("File created successfully")

Output:
Hello World ! the file has more content!
<class 'str'>
Hell
Hello World ! the file has more content!
Traceback (most recent call last):
FileExistsError: [Errno 17] File exists: 'PPLab.txt'
b) Write a Python code to merge two given file contents into a third file
data = data2 = "";

# Reading data from file1


with open('file1.txt') as fp:
data = fp.read()

# Reading data from file2


with open('file2.txt') as fp:
data2 = fp.read()

# Merging 2 files
# To add the data of file2
# from next line
data += "\n"
data += data2

with open ('file3.txt', 'w') as fp:


fp.write(data)

Output:
open and check file3.txt

c) Write a function that reads a file file1 and displays the number of words, number of vowels, blank
spaces,lower case letters and uppercase letters

print("Enter the Name of File: ")

fileName = str(input())
fileHandle = open(fileName, "r")
tot = 0
for char in fileHandle.read():
if char= =' ':
tot = tot+1

print(f"There are {tot} blank spaces in file")


fileHandle.close()
fileHandle = open(fileName, "r")
tot=1

for char in fileHandle.read():


if char==' 'or char=='\n':
tot=tot+1

print(f"There are {tot-1} words in file")


fileHandle.close()
fileHandle = open(fileName, "r")
vowels=['a','e','i','o','u','A','E','I','O','U']
tot=0
for char in fileHandle.read():
if char in vowels:
tot=tot+1
print(f"There are {tot} vowels in file")

fileHandle.close()
fileHandle = open(fileName, "r")
totl=0
totu=0
for char in fileHandle.read():
if char>='a' and char<='z':
totl=totl+1
elif char>='A' and char<='Z':
totu=totu+1
print(f"there are {totl} lower case letters and {totu} uppercase letters")
fileHandle.close()
output
Enter the Name of File:
file4.py
There are 60 blank spaces in file
There are 68 words in file
There are 57 vowels in file
there are 167 lower case letters and 0 uppercase letters
12. Python program to practice some basic library modules
a) Numpy
b) Pandas

a) Explanation –NumPy Module


Addition
The add() function sums the content of two arrays, and return the results in a new array.
Subtraction
The subtract() function subtracts the values from one array with the values from another array, and
return the results in a new array.
Multiplication
The multiply() function multiplies the values from one array with the values from another array, and
return the results in a new array.
Division
The divide() function divides the values from one array with the values from another array, and
return the results in a new array.
Power
The power() function rises the values from the first array to the power of the values of the second
array, and return the results in a new array.

a) Source Code – Write python program to demonstrate the basic functionality of NumPy Module

print("\n*********Addition*********")

import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([2, 1, 2, 3, 13, 5])
newarr = np.add(arr1, arr2)
print(newarr)

print("\n*********Subtraction*********")
newarr = np.subtract(arr1, arr2)
print(newarr)
print("\n*********Multiplication*********")
newarr = np.multiply(arr1, arr2)
print(newarr)

print("\n*********Division*********")
newarr = np.divide(arr1, arr2)
print(newarr)

print("\n*********Power*********")
newarr = np.power(arr1, arr2)
print(newarr)
Output:
*********Addition*********
[12 12 14 16 27 20]

*********Subtraction*********
[ 8 10 10 10 1 10]

*********Multiplication*********
[ 20 11 24 39 182 75]

*********Division*********
[ 5. 11. 6. 4.33333333 1.07692308 3. ]

*********Power*********
[ 100 11 144 2197
793714773254144 759375]

b) Explanation of –SciPy Module


SciPy is a scientific computation library that uses NumPy underneath.
SciPy stands for Scientific Python.
It provides more utility functions for optimization, stats and signal processing.
Like NumPy, SciPy is open source so we can use it freely.
Constants in SciPy:
As SciPy is more focused on scientific implementations, it provides many built-in scientific
constants.These constants can be helpful when you are working with Data Science.
PI is an example of a scientific constant.
Constant Units
A list of all units under the constants module can be seen using the dir() function.
b) Write python program to demonstrate the basic functionality of SciPy Module
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50, 60])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.subtract(arr1, arr2)
print(newarr)
print("*********Multiplication*********")

newarr = np.multiply(arr1, arr2)


print(newarr)

print("*********Division*********")
newarr = np.divide(arr1, arr2)
print(newarr)
print("*********Power*********")
newarr = np.power(arr1, arr2)
print(newarr)
Output:
[-10 -1 8 17 26 35]
*********Multiplication*********
[ 200 420 660 920 1200 1500]
*********Division*********
[0.5 0.95238095 1.36363636 1.73913043 2.08333333 2.4 ]
*********Power*********
[ 7766279631452241920 -5135277853620830208 8433224401192747008
0 8120319428677074944 6213841585864441856]

You might also like