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

python_lab

Uploaded by

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

python_lab

Uploaded by

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

KLE SOCIETY’s

S. NIJALINGAPPA COLLEGE
DEPARTMENT OF COMPUTER SCIENCE
Bachelor of Computer Applications

Python LAB Manual

1. write a program to demonstrate basic datatype in phython:

a=10
b="Python"
c = 10.5
d=2.14j
e=True
print("Data type of Variable a :",type(a))
print("Data type of Variable b :",type(b))
print("Data type of Variable c :",type(c))
print("Data type of Variable d :",type(d))
print("Data type of Variable e :",type(e))

Output:

Data type of Variable a : <class 'int'>


Data type of Variable b : <class 'str'>
Data type of Variable c : <class 'float'>
Data type of Variable d : <class 'complex'>
Data type of Variable e : <class 'bool'>
2. Create a list and perform the following methods.
a) insert( ) b) remove( ) c) append( ) d) pop( ) e) clear( )

a=[1,3,5,6,7,4,"hello"]
print(a)
#insert()
a.insert(3,20)
print(a)
#remove()
a.remove(7)
print(a)
#append()
a.append("hi")
print(a)
c=len(a)
print(c)
#pop()
a.pop()
print(a)
a.pop(6)
print(a)
# clear()
a.clear()
print(a)

output:
[1, 3, 5, 6, 7, 4, 'hello']
[1, 3, 5, 20, 6, 7, 4, 'hello']
[1, 3, 5, 20, 6, 4, 'hello']
[1, 3, 5, 20, 6, 4, 'hello', 'hi']
8
[1, 3, 5, 20, 6, 4, 'hello']
[1, 3, 5, 20, 6, 4]
[]
3. Create a tuple and perform the following methods.

a) Add items b) len( ) c) Check for item in tuple d) Access items

#creating a tuple
rainbow=("v","i","b","g","y","o","r")
print(rainbow)
colour=("violet","blue","green","yellow","orange","red")
print(colour)
# Add items in tuples
rainbow_colour=rainbow+colour
print(rainbow_colour)
#length of the tuple
c=len(rainbow_colour)
print(c)
#Access items in tuple
print("rainbow[2]:",rainbow[2])
"""rainbow[1:3] means all the items in rainbow tuple
starting from an index value of 1 up to an index value of 4"""
print("rainbow[1:3]",rainbow[1:3])
print("rainbow[0:4]",rainbow[0:4])

output:

('v', 'i', 'b', 'g', 'y', 'o', 'r')


('violet', 'blue', 'green', 'yellow', 'orange', 'red')
('v', 'i', 'b', 'g', 'y', 'o', 'r', 'violet', 'blue', 'green', 'yellow', 'orange', 'red')
13
rainbow[2]: b
rainbow[1:3] ('i', 'b')
rainbow[0:4] ('v', 'i', 'b', 'g')
4. Create a dictionary and apply the following methods.

1. Print the dictionary items 2. Access items 3. Use get( )


4. Change Values 5. Use len( )

#Source code:
# creating a dictionary
college={'name': "QIS", 'code': "INDIA",'pincode': 560050 }
print(college)
#adding items to dictionary
college["location"] = "IBP"
print(college)
#changing values of a key
college["location"] = "vijayawada"
print(college)
#know the length using len()
print("length of college is:",len(college))
#Acess items
print("college['name']:",college['name'])
# use get ()
x=college.get('pincode')
print(x)
#to copy the same dictionary use copy()
mycollege= college.copy()
print(mycollege)

Output:

{'name': 'QIS', 'code': 'QISIT', 'pincode': 560050}


{'name': 'QIS', 'code': ' QISIT ', 'pincode': 560050, 'location': 'IBP'}
{'name': 'QIS', 'code': ' QISIT ', 'pincode': 560050, 'location': 'vijayawada'}
length of college is: 4
college['name']: QIS
560050
{'name': 'QIS', 'code': ' QISIT ', 'pincode': 560050, 'location': 'vijayawada'}
5. Write a programto create a menu with the following options
1. TO PERFORM ADDITITON 2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPICATION 4. TO PERFORM DIVISION
Accepts users input and perform the operation accordingly. Use functions
with arguments.

#print("Program to create a menu with the following options")


#1. TO PERFORM ADDITION
#2. TO PERFORM SUBTRACTION
#3. TO PERFORM MULTIPLICATION
#4. TO PERFORM DIVISION

def add(n1,n2):
return n1+n2
def sub(n1,n2):
return n1-n2
def mul(n1,n2):
return n1*n2
def div(n1,n2):
return n1/n2

print("Welcome to the Arithmetic Program")


choice =1
while(choice!=0):
x = int(input(" Enter the first number\n"))
y = int(input(" Enter the second number\n"))
print("1. TO PERFORM ADDITION")
print("2. TO PERFORM SUBTRACTION")
print("3. TO PERFORM MULTIPLICATION")
print("4. TO PERFORM DIVISION")
print("0. To Exit")
choice = int(input("Enter your choice"))
if choice == 1:
print(x, "+" ,y ,"=" ,add(x,y))
elif choice == 2:
print(x, "-" ,y ,"=" ,sub(x,y))
elif choice == 3:
print(x, "*" ,y ,"=" ,mul(x,y))
elif choice == 4:
print(x, "%" ,y ,"=" ,div(x,y))
elif choice ==0:
print("Exit")
else: print("Invalid Choice");

output:

Welcome to the Arithmetic Program


Enter the first number
45
Enter the second number
56
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
0. To Exit
Enter your choice 1
45 + 56 = 101
Enter the first number
23
Enter the second number
12
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
0. To Exit
Enter your choice 2
23 - 12 = 11
Enter the first number
2
Enter the second number
45
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
0. To Exit
Enter your choice 3
2 * 45 = 90
Enter the first number
34
Enter the second number
2
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
0. To Exit
Enter your choice 4
34 % 2 = 17.0
Enter the first number
2
Enter the second number
3
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
0. To Exit
Enter your choice0
Exit
6.Write a Program to print a number is Positive / Negative using if-else

print("Program to print a number is Positive / Negative")


choice =1
while(choice!=0):
number=int(input("Enter a Number"))
if number >0:
print("The Number",number,"is Positive")
else:
print("The Number",number, "is negative")
choice=int(input("Do you wish to continue 1/0"))

output:

Program to print a number is Positive / Negative


Enter a Number 67
The Number 67 is Positive
Do you wish to continue 1/0 1
Enter a Number -90
The Number -90 is negative
Do you wish to continue 1/0 0
7. Write a program for filter() to filter only even numbers from a given list.

def find_even_numbers(list_items):
print(" The EVEN numbers in the list are: ")
for item in list_items:
if item%2==0:
print(item)
def main():
list1=[2,3,6,8,48,97,56]
find_even_numbers(list1)
if __name__=="__main__":
main()

Output:

The EVEN numbers in the list are:


2
6
8
48
56
7. Write a program for filter() to filter only even numbers from a given list.

Source Code:

def even(x):
return x % 2 == 0

a=[2,5,7,16,8,9,14,78]
result=filter(even,a)
print(" original List is :",a)
print(" Filtered list is : ",list(result))

output:

original List is : [2, 5, 7, 16, 8, 9, 14, 78]


Filtered list is : [2, 16, 8, 14, 78]
8.Write a python program to print date, time for today and now

import datetime
a=datetime.datetime.today()
b=datetime.datetime.now()
print(b)
print(“ today date is :”,a)
print(“ current year :”,a.year)
print(“ current month :”,a.month)
print(“ current day :”,a.day)
print(a.strftime(“%a”))
print(a.strftime(“%b”))
print(a.strftime(“%c”))

Output:

2022-11-30 17:18:52.879383
2022-11-30 17:18:52.879382
2022
11
30
Wed
Nov
Wed nov 30 17:18:52.87938 2022
9. Write a python program to add some days to your present date and print the date
added.

from datetime import datetime


from datetime import timedelta
from datetime import date

# taking input as the current date


# today() method is supported by date
# class in datetime module
Begindatestring = date.today()

# print begin date


print("Beginning date")
print(Begindatestring)

# calculating end date by adding 4 days


Enddate = Begindatestring + timedelta(days=10)

# printing end date


print("Ending date")
print(Enddate)

Output:

Beginning date
2022-12-05
Ending date
2022-12-15
10. Write a program to count the number of characters in
a string and store them in a dictionary data structure.

def construct_character_dict(word):
character_count_dict=dict()
for each_character in word:
character_count_dict[each_character]=character_count_dict.get(each_character,0)+1
sorted_list_keys=sorted(character_count_dict.keys())
for each_key in sorted_list_keys:
print(each_key,character_count_dict.get(each_key))
def main():
word=input("enter a string")
construct_character_dict(word)
if __name__=="__main__":
main()

Output:

enter a string KLESNCBCA

1
A 1
B 1
C 2
E 1
K 1
L 1
N 1
S 1
11. Write a python program count frequency of characters in a given file

Source Code:

import collections
import pprint
file_input = input('File Name: ')
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)

Output:

File Name: gfg1.txt


Counter ({'L': 3,
'E': 3,
'C': 3,
'K': 1,
'B': 1,
'A': 1,
'S': 1,
'N': 1,
'O': 1,
'G': 1})
12. Using a numpy module create an array and check the following:
1. Type of array 2. Axes of array
3. Shape of array 4. Type of elements in array

import numpy as np
arr=np.array([[1,2,3],[4,2,5]])
print("Array is of type:",type(arr))
print("no.of dimensions:",arr.ndim)
print("Shape of array:",arr.shape)
print("Size of array:",arr.size)
print("Array stores elements of type:",arr.dtype)

Output:

Array is of type: <class 'numpy.ndarray'>


no.of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int32
13.Write a python program to concatenate the dataframes with two different
objects.

import pandas as pd
one=pd.DataFrame({'Name':['teju','gouri'], 'age':[19,20]},
index=[1,2])
two=pd.DataFrame({'Name':['suma','nammu'], 'age':[20,21]},
index=[3,4])
print(pd.concat([one,two]))

Output:

Name age
1 teju 19
2 gouri 20
3 suma 20
4 nammu 21
14. Write a python code to read a csv file using pandas module and print frist five and last
five lines of a file.

Source Code:

import pandas as pd
pd.set_option('display.max_rows', 50)
pd.set_option('display.max_columns', 50)
diamonds = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-
data/master/diamonds.csv')
print("First 5 rows:")
print(diamonds.head())
print("last 5 rows:")
print(diamonds.tail())

Output:

First 5 rows:
carat cut color clarity depth table price x y z
0 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43
1 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31
2 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31
3 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63
4 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75
last 5 rows:
carat cut color clarity depth table price x y z
53935 0.72 Ideal D SI1 60.8 57.0 2757 5.75 5.76 3.50
53936 0.72 Good D SI1 63.1 55.0 2757 5.69 5.75 3.61
53937 0.70 Very Good D SI1 62.8 60.0 2757 5.66 5.68 3.56
53938 0.86 Premium H SI2 61.0 58.0 2757 6.15 6.12 3.74
53939 0.75 Ideal D SI2 62.2 55.0 2757 5.83 5.87 3.64
15. WAP which accepts the radius of a circle from user and compute the area(
Use math module)

import math as M
radius = float(input("Enter the radius of the circle"))
area_of_circle = M.pi*radius*radius
circumference_of_circle = 2*M.pi*radius
print("the area of circle is", area_of_circle)
print("the circumference of circle is", circumference_of_circle)

Output:

Enter the radius of the circle 45


The area of circle is 6361.725123519332
The circumference of circle is 282.7433388230814

You might also like