Pp Lab Manual
Pp Lab Manual
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.
Output
Python Programming
b) Write a python program to read integer, float & string values and display them on the screen
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.
Output:
Please enter temperature in fahrenheit:44
Temperature in celsius: 6.666666666666667
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.
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
si=p*t*r/100
print("simple intrest=",si)
Output:
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
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
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
# 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:
Output:
Enter a number: 23
Positive number
b) Write a python program to find the largest number among three numbers.
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.
a, b = b, a
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.
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.
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.
revs_number = 0
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
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
Output:
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
Output:
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 "
str4 = "abc"
# printing result
print("All substrings of string are : " + str(res))
Output:
Output:
# Declaring a function
def my_function(fname, lname):
print(fname + " " + lname)
# Calling function
my_function("Albert", "Einstein")
Output:
Albert Einstein
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
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)
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))
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()
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]
Output:
Even numbers in the list: [2, 4, 6, 8, 10]
c) Write a Python Program to Make a Simple Calculator.
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
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 )
#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 )
#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 )
print("Create a list")
mylist = ["apple", "banana", "cherry"]
print(mylist)
print("Remove an item")
mylist = ["apple", "banana", "cherry"]
mylist.remove("banana")
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
[]
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)
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
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
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.
# 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()
# 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:
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
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:
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:
a) Write a python program to open and write “hello world” into a file and check the access
permissions to that file?
#stores all the data of the file into the variable content
content = f.read(4)
# 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 = "";
# Merging 2 files
# To add the data of file2
# from next line
data += "\n"
data += data2
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
fileName = str(input())
fileHandle = open(fileName, "r")
tot = 0
for char in fileHandle.read():
if char= =' ':
tot = tot+1
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) 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]
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]