SlideShare a Scribd company logo
KLE Society’s S Nijalingappa College
Bachelor of Computer Application
III Semester: Python Programming Language
1. Write a program to demonstrate basic data type in python:
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("The list created is", a)
#insert()
a.insert(3,20)
print("Insert the element 20 at index position 3. The modified list isn", a)
#remove()
a.remove(7)
print("Remove the element 7 from the list. The modified list is n", a)
#append()
a.append("hi")
print("Appended the list with a stringn", a)
c=len(a)
print("The length of the list is n", c)
#pop()
a.pop()
print("After popping the element from the list n", a)
a.pop(6)
print("After popping the element at index position 6 from the list, modified list is
n", a)
# clear()
a.clear()
print("The cleared list is n", a)
Output:
The list created is [1, 3, 5, 6, 7, 4, 'hello']
Insert the element 20 at index position 3. The modified list is
[1, 3, 5, 20, 6, 7, 4, 'hello']
Remove the element 7 from the list. The modified list is
[1, 3, 5, 20, 6, 4, 'hello']
Appended the list with a string
[1, 3, 5, 20, 6, 4, 'hello', 'hi']
The length of the list is : 8
After popping the element from the list
[1, 3, 5, 20, 6, 4, 'hello']
After popping the element at index position 6 from the list, modified list is
[1, 3, 5, 20, 6, 4]
The cleared list is
[]
3. Create a tuple and perform the following methods.
a) Add items b) len( ) c) Check for item in tuple d) Access items
rainbow=("v","i","b","g","y","o","r")
print("The tuple of alphabets creating a rainbow is n", rainbow)
colour=("violet","Indigo","blue","green","yellow","orange","red")
print("The tuple of colours in a rainbow is n", colour)
# Add items in tuples
rainbow_colour=rainbow+colour
print("Concatenating the two tuples we get n", rainbow_colour)
#length of the tuple
c=len(rainbow_colour)
print("The length of the concatenated tuple is", c)
# check for item in tuple
print("Item prsent in the list it returns True Or Else False")
if "blue" in rainbow_colour:
print(True)
else:
print(False)
#Access items in tuple
print("Printing the item rainbow[2]: of tuple",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 3 excluding 3"""
print("Printing the items rainbow[1:3]",rainbow[1:3])
print("Printing the items rainbow[0:4]",rainbow[0:4])
Output:
The tuple of alphabets creating a rainbow is
('v', 'i', 'b', 'g', 'y', 'o', 'r')
The tuple of colours in a rainbow is
('violet', 'Indigo', 'blue', 'green', 'yellow', 'orange', 'red')
Concatenating the two tuples we get
('v', 'i', 'b', 'g', 'y', 'o', 'r', 'violet', 'Indigo', 'blue', 'green', 'yellow', 'orange', 'red')
The length of the concatenated tuple is 14
If Item present in the list it returns True Or Else False
True
Printing the item rainbow[2]: of tuple b
Printing the items rainbow[1:3] ('i', 'b')
Printing the items 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': "QISIT",'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 SUBTRACTION3. TO
PERFORM MULTIPICATION
4. TO PERFORM DIVISION
Accepts users input and perform the operation accordingly. Use functions
with arguments.
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")
print("1. TO PERFORM ADDITION")
print("2. TO PERFORM SUBTRACTION")
print("3. TO PERFORM MULTIPLICATION")
print("4. TO PERFORM DIVISION")
print("0. To Exit")
x = int(input(" Enter the first numbern"))
y = int(input(" Enter the second numbern"))
choice =1
while(choice!=0):
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
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
0. To Exit
Enter the first number
12
Enter the second number
4
Enter your choice : 1
12 + 4 = 16
Enter your choice : 2
12 - 4 = 8
Enter your choice : 3
12 * 4 = 48
Enter your choice : 4
12 % 4 = 3.0
Enter your choice : 5
Invalid Choice
Enter your choice : 0
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")
elif number <0:
print("The Number",number, "is negative")
else:
print("ZERO is a Neutral number ")
choice=int(input("Do you wish to continue 1/0 :"))
Output:
Program to print a number is Positive / Negative
Enter a Number : 5
The Number 5 is Positive
Do you wish to continue 1/0 : 1
Enter a Number : -8
The Number -8 is negative
Do you wish to continue 1/0 : 1
Enter a Number : 0
ZERO is a Neutral number
Do you wish to continue 1/0 : 0
7. Write a program to filter only even numbers from a given list.(without
using filter function).
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.
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("now date and time is:",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:
now date and time is: 2023-02-28 19:39:01.936566
Today date is : 2023-02-28 19:39:01.936567
current year : 2023
current month : 2
current day : 28
Tue
Feb
Tue Feb 28 19:39:01 2023
python_lab_manual_final (1).pdf
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
2023-02-28
Ending date
2023-03-10
10. Write a program to count the number of characters ina 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
print(character_count_dict)
def main():
word=input("enter a string :")
construct_character_dict(word)
if __name__=="__main__":
main()
Output:
enter a string :klebca
{'k': 1, 'l': 1, 'e': 1, 'b': 1, 'c': 1, 'a': 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: gfg.txt
Counter({'L': 4,
'E': 3,
' ': 3,
'A': 3,
'.': 2,
'N': 2,
'I': 2,
'G': 2,
'P': 2,
'K': 1,
"'": 1,
'S': 1,
'J': 1,
'C': 1,
'O': 1})
12. Using a numpy module create an array and check the following:
1. Type of array 2. Axes of array3. 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('List.csv')
print("First 5 rows:")
print(diamonds.head())
print("Last 5 rows:")
print(diamonds.tail())
Output:
First 5 rows:
REG NO NAME COURSE FEES LANGUAGE
0 101 jagan BCA 100000 KAN
1 102 jithin Bcom 100000 HIN
2 103 preethi BCA 100000 KAN
3 104 manoj BBA 30000 HIN
4 105 nikitha MBA 200000 TEL
Last 5 rows:
REG NO NAME COURSE FEES LANGUAGE
6 107 pavan ts Mtech 600000 TAMIL
7 108 ramu BSC 45000 KAN
8 109 radha BCA 100000 KAN
9 110 sita BCA 100000 KAN
10 111 raj BCom 100000 TEL
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

More Related Content

Similar to python_lab_manual_final (1).pdf (20)

PDF
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
parthp5150s
 
PDF
Well Grounded Python Coding - Revision 1 (Day 1 Handouts)
Worajedt Sitthidumrong
 
PDF
Well Grounded Python Coding - Revision 1 (Day 1 Slides)
Worajedt Sitthidumrong
 
DOCX
python file for easy way practicle programs
vineetdhand2004
 
PDF
GE3151_PSPP_UNIT_4_Notes
Guru Nanak Technical Institutions
 
PDF
Python tutorial
Andrei Tomoroga
 
PDF
Python lists &amp; sets
Aswini Dharmaraj
 
PDF
Python Part 1
Mohamed Ramadan
 
PDF
Python Usage (5-minute-summary)
Ohgyun Ahn
 
PDF
Python Cheat Sheet
Muthu Vinayagam
 
PDF
Mementopython3 english
ssuser442080
 
PDF
Python3
Sourodip Kundu
 
PDF
Mementopython3 english
yassminkhaldi1
 
DOCX
Python Laboratory Programming Manual.docx
ShylajaS14
 
PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
DOCX
cs class 12 project computer science .docx
AryanSheoran1
 
PDF
Python_ 3 CheatSheet
Dr. Volkan OBAN
 
PDF
Introduction to python cheat sheet for all
shwetakushwaha45
 
PDF
paython practical
Upadhyayjanki
 
PDF
Xi CBSE Computer Science lab programs
Prof. Dr. K. Adisesha
 
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
parthp5150s
 
Well Grounded Python Coding - Revision 1 (Day 1 Handouts)
Worajedt Sitthidumrong
 
Well Grounded Python Coding - Revision 1 (Day 1 Slides)
Worajedt Sitthidumrong
 
python file for easy way practicle programs
vineetdhand2004
 
GE3151_PSPP_UNIT_4_Notes
Guru Nanak Technical Institutions
 
Python tutorial
Andrei Tomoroga
 
Python lists &amp; sets
Aswini Dharmaraj
 
Python Part 1
Mohamed Ramadan
 
Python Usage (5-minute-summary)
Ohgyun Ahn
 
Python Cheat Sheet
Muthu Vinayagam
 
Mementopython3 english
ssuser442080
 
Mementopython3 english
yassminkhaldi1
 
Python Laboratory Programming Manual.docx
ShylajaS14
 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
cs class 12 project computer science .docx
AryanSheoran1
 
Python_ 3 CheatSheet
Dr. Volkan OBAN
 
Introduction to python cheat sheet for all
shwetakushwaha45
 
paython practical
Upadhyayjanki
 
Xi CBSE Computer Science lab programs
Prof. Dr. K. Adisesha
 

Recently uploaded (20)

PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Ad

python_lab_manual_final (1).pdf

  • 1. KLE Society’s S Nijalingappa College Bachelor of Computer Application III Semester: Python Programming Language 1. Write a program to demonstrate basic data type in python: 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. 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("The list created is", a) #insert() a.insert(3,20) print("Insert the element 20 at index position 3. The modified list isn", a) #remove() a.remove(7) print("Remove the element 7 from the list. The modified list is n", a) #append() a.append("hi") print("Appended the list with a stringn", a) c=len(a) print("The length of the list is n", c) #pop() a.pop() print("After popping the element from the list n", a) a.pop(6) print("After popping the element at index position 6 from the list, modified list is n", a) # clear() a.clear() print("The cleared list is n", a) Output: The list created is [1, 3, 5, 6, 7, 4, 'hello'] Insert the element 20 at index position 3. The modified list is [1, 3, 5, 20, 6, 7, 4, 'hello'] Remove the element 7 from the list. The modified list is [1, 3, 5, 20, 6, 4, 'hello'] Appended the list with a string
  • 3. [1, 3, 5, 20, 6, 4, 'hello', 'hi'] The length of the list is : 8 After popping the element from the list [1, 3, 5, 20, 6, 4, 'hello'] After popping the element at index position 6 from the list, modified list is [1, 3, 5, 20, 6, 4] The cleared list is [] 3. Create a tuple and perform the following methods. a) Add items b) len( ) c) Check for item in tuple d) Access items rainbow=("v","i","b","g","y","o","r") print("The tuple of alphabets creating a rainbow is n", rainbow) colour=("violet","Indigo","blue","green","yellow","orange","red") print("The tuple of colours in a rainbow is n", colour) # Add items in tuples rainbow_colour=rainbow+colour print("Concatenating the two tuples we get n", rainbow_colour) #length of the tuple c=len(rainbow_colour) print("The length of the concatenated tuple is", c) # check for item in tuple print("Item prsent in the list it returns True Or Else False") if "blue" in rainbow_colour: print(True) else: print(False) #Access items in tuple print("Printing the item rainbow[2]: of tuple",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 3 excluding 3""" print("Printing the items rainbow[1:3]",rainbow[1:3]) print("Printing the items rainbow[0:4]",rainbow[0:4])
  • 4. Output: The tuple of alphabets creating a rainbow is ('v', 'i', 'b', 'g', 'y', 'o', 'r') The tuple of colours in a rainbow is ('violet', 'Indigo', 'blue', 'green', 'yellow', 'orange', 'red') Concatenating the two tuples we get ('v', 'i', 'b', 'g', 'y', 'o', 'r', 'violet', 'Indigo', 'blue', 'green', 'yellow', 'orange', 'red') The length of the concatenated tuple is 14 If Item present in the list it returns True Or Else False True Printing the item rainbow[2]: of tuple b Printing the items rainbow[1:3] ('i', 'b') Printing the items rainbow[0:4] ('v', 'i', 'b', 'g')
  • 5. 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': "QISIT",'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'}
  • 6. 5. Write a programto create a menu with the following options 1. TO PERFORM ADDITITON 2.TO PERFORM SUBTRACTION3. TO PERFORM MULTIPICATION 4. TO PERFORM DIVISION Accepts users input and perform the operation accordingly. Use functions with arguments. 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") print("1. TO PERFORM ADDITION") print("2. TO PERFORM SUBTRACTION") print("3. TO PERFORM MULTIPLICATION") print("4. TO PERFORM DIVISION") print("0. To Exit") x = int(input(" Enter the first numbern")) y = int(input(" Enter the second numbern")) choice =1 while(choice!=0): 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:
  • 7. print("Exit") else: print("Invalid Choice"); Output: Welcome to the Arithmetic Program 1. TO PERFORM ADDITION 2. TO PERFORM SUBTRACTION 3. TO PERFORM MULTIPLICATION 4. TO PERFORM DIVISION 0. To Exit Enter the first number 12 Enter the second number 4 Enter your choice : 1 12 + 4 = 16 Enter your choice : 2 12 - 4 = 8 Enter your choice : 3 12 * 4 = 48 Enter your choice : 4 12 % 4 = 3.0 Enter your choice : 5 Invalid Choice Enter your choice : 0 Exit
  • 8. 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") elif number <0: print("The Number",number, "is negative") else: print("ZERO is a Neutral number ") choice=int(input("Do you wish to continue 1/0 :")) Output: Program to print a number is Positive / Negative Enter a Number : 5 The Number 5 is Positive Do you wish to continue 1/0 : 1 Enter a Number : -8 The Number -8 is negative Do you wish to continue 1/0 : 1 Enter a Number : 0 ZERO is a Neutral number Do you wish to continue 1/0 : 0
  • 9. 7. Write a program to filter only even numbers from a given list.(without using filter function). 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. 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]
  • 10. 8.Write a python program to print date, time for today and now. import datetime a=datetime.datetime.today() b=datetime.datetime.now() print("now date and time is:",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: now date and time is: 2023-02-28 19:39:01.936566 Today date is : 2023-02-28 19:39:01.936567 current year : 2023 current month : 2 current day : 28 Tue Feb Tue Feb 28 19:39:01 2023
  • 12. 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 2023-02-28 Ending date 2023-03-10
  • 13. 10. Write a program to count the number of characters ina 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 print(character_count_dict) def main(): word=input("enter a string :") construct_character_dict(word) if __name__=="__main__": main() Output: enter a string :klebca {'k': 1, 'l': 1, 'e': 1, 'b': 1, 'c': 1, 'a': 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)
  • 14. Output: File Name: gfg.txt Counter({'L': 4, 'E': 3, ' ': 3, 'A': 3, '.': 2, 'N': 2, 'I': 2, 'G': 2, 'P': 2, 'K': 1, "'": 1, 'S': 1, 'J': 1, 'C': 1, 'O': 1}) 12. Using a numpy module create an array and check the following: 1. Type of array 2. Axes of array3. 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)
  • 15. 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
  • 16. 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
  • 17. 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('List.csv') print("First 5 rows:") print(diamonds.head()) print("Last 5 rows:") print(diamonds.tail()) Output: First 5 rows: REG NO NAME COURSE FEES LANGUAGE 0 101 jagan BCA 100000 KAN 1 102 jithin Bcom 100000 HIN 2 103 preethi BCA 100000 KAN 3 104 manoj BBA 30000 HIN 4 105 nikitha MBA 200000 TEL Last 5 rows: REG NO NAME COURSE FEES LANGUAGE 6 107 pavan ts Mtech 600000 TAMIL 7 108 ramu BSC 45000 KAN 8 109 radha BCA 100000 KAN 9 110 sita BCA 100000 KAN 10 111 raj BCom 100000 TEL
  • 18. 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