Python Lab Course File
Python Lab Course File
Course : B.Tech
6. Lesson Plan
7. Roll List
9. Internal Marks
10.External Marks
Software Requirements :
1. IDLE : https://www.python.org/downloads
2. Anaconda : https://www.anaconda.com/
3. Microsoft Visual Studio : https://visualstudio.microsoft.com/downloads/
List of Experiments:
1) Write a program that asks the user for a weight in kilograms and converts it to pounds.
There are 2.2 pounds in a kilograms.
2) Write a program that asks the user to enter three numbers (use three separate input
statements). Create variables called total and average that hold the sum and average of the
three numbers and print out the values of total and average.
3) Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, . . . , 83, 86,
89. 4) Write a program that asks the user for their name and how many times to print it. The
program should print out the user’s name the specified number of times.
5) Use a forloop to print a triangle like the one below. Allow the user to specify how high
the triangle should be.
*
**
***
****
6) Generate a random number between 1 and 10. Ask the user to guess the number and
print a message based on whether they get it right or not.
7) Write a program that asks the user for two numbers and prints Close if the numbers are
within .001 of each other and Not close otherwise.
8) Write a program that asks the user to enter a word and prints out whether that word
contains any vowels.
9) Write a program that asks the user to enter two strings of the same length. The program
should then check to see if the strings are of the same length. If they are not, the program
should print an appropriate message and exit. If they are of the same length, the program
should alternate the characters of the two strings. For example, if the user enters
abcdeandABCDE the program should print out AaBbCcDdEe.
10) Write a program that asks the user for a large integer and inserts commas into it
according to the standard American convention for commas in large numbers. For instance,
if the user enters 1000000, the output should be 1,000,000.
11) In algebraic expressions, the symbol for multiplication is often left out, as in 3x+4y or
3(x+5). Computers prefer those expressions to include the multiplication symbol, like
3*x+4*y or 3*(x+5). Write a program that asks the user for an algebraic expression and
then inserts multiplication symbols where appropriate.
12) Write a program that generates a list of 20 random numbers between 1 and 100. (a)
Print the list. (b) Print the average of the elements in the list. (c) Print the largest and
smallest values in the list. (d) Print the second largest and second smallest entries in the list
(e) Print how many even numbers are in the list.
13) Write a program that asks the user for an integer and creates a list that consists of the
factors of that integer.
14) Write a program that generates 100 random integers that are either 0 or 1. Then find the
longest run of zeros, the largest number of zeros in a row. For instance, the longest run of
zeros in [1,0,1,1,0,0,0,0,1,0,0] is 4.
15) Write a program that removes any repeated items from a list so that each item appears at
most once. For instance, the list [1,1,2,3,4,3,0,0] would become [1,2,3,4,0].
16) Write a program that asks the user to enter a length in feet. The program should then
give the user the option to convert from feet into inches, yards, miles, millimeters,
centimeters, meters, or kilometers. Say if the user enters a 1, then the program converts to
inches, if they enter a 2, then the program converts to yards, etc. While this can be done
with if statements,it is much shorter with lists and it is also easier to add new conversions if
you use lists.
17) Write a function called sum_digitsthat is given an integer num and returns the sum of
the digits of num.
18) Write a function called first_diff that is given two strings and returns the first location in
which the strings differ. If the strings are identical, it should return -1.
19) Write a function called number_of_factors that takes an integer and returns how many
factors the number has.
20) Write a function called is_sorted that is given a list and returns True if the list is sorted
and False otherwise.
21) Write a function called root that is given a number x and an integer n and returns x1/n.
In the function definition, set the default value of n to 2.
22) Write a function called primes that is given a number n and returns a list of the first n
primes. Let the default value of n be 100.
23) Write a function called merge that takes two already sorted lists of possibly different
lengths, and merges them into a single sorted list. (a) Do this using the sort method. (b) Do
this without using the sort method.
24) Write a program that asks the user for a word and finds all the smaller words that can be
made from the letters of that word. The number of occurrences of a letter in a smaller word
can’t exceed the number of occurrences of the letter in the user’s word.
25) Write a program that reads a file consisting of email addresses, each on its own line.
Your program should print out a string consisting of those email addresses separated by
semicolons.
26) Write a program that reads a list of temperatures from a file called temps.txt, converts
those temperatures to Fahrenheit, and writes the results to a file called ftemps.txt.
27) Write a class called Product. The class should have fields called name, amount, and
price, holding the product’s name, the number of items of that product in stock, and the
regular price of the product. There should be a method get_pricethat receives the number of
items to be bought and returns a the cost of buying that many items, where the regular price
is charged for orders of less than 10 items, a 10% discount is applied for orders of between
10 and 99 items, and a 20% discount is applied for orders of 100 or more items. There
should also be a method called make_purchasethat receives the number of items to be
bought and decreases amount by that much.
28) Write a class called Time whose only field is a time in seconds. It should have a method
called convert_to_minutesthat returns a string of minutes and seconds formatted as in the
following example: if seconds is 230, the method should return '5:50'. It should also have a
method called convert_to_hoursthat returns a string of hours, minutes, and seconds
formatted analogously to the previous method.
29) Write a class called Converter. The user will pass a length and a unit when declaring an
object from the class—for example, c = Converter(9,'inches'). The possible units are inches,
feet, yards, miles, kilometers, meters, centimeters, and millimeters. For each of these units
there should be a method that returns the length converted into those units. For example,
using the Converter object created above, the user could call c.feet() and should get 0.75 as
the result.
30) Write a Python class to implement pow(x, n).
31) Write a Python class to reverse a string word by word.
32) Write a program that opens a file dialog that allows you to select a text file. The
program then displays the contents of the file in a textbox.
33) Write a program to demonstrate Try/except/else.
34) Write a program to demonstrate try/finally and with/as
Additional Experiments:
1) Write a python class to implement employee details and display using objects.
2) Write a python class to demonstrate contructor overloading and overriding.
3. PO, PEOs & PSO statements
PROGRAM OUTCOMES (POs) FOR UG COURSES
The program is targeted at developing the following competencies, skills and abilities
amongst students:
PO1: An ability to apply knowledge of Mathematics, Science and Engineering to give the
solution for Complex Engineering Problems
PO3: An ability to design a System, Component or Process to meet desired needs within
various realistic constraints of socio-economic sustainability
PO4: An ability to use research-based knowledge and research methods, including design,
analysis and interpretation of data and synthesis of the information to provide valid
conclusions to complex problems
PO5: An ability to use the Techniques, Skills and Modern Engineering Tools necessary
for engineering practice
PO8: An ability to understand professional and ethical responsibility while performing the
job responsibilities
PO12: An ability to recognition the need for and ability to engage in Continual Learning
Program Educational Objectives
Program Educational Objectives of the UG in COMPUTER SCIENCE & ENGINEERING
are:
PEO 1: Graduate shall be an efficient Software Developer in diverse fields and will be a
Successful Professional or pursue Higher Studies
PEO 2: Graduates shall be a Lifetime Learner, capable to adapt to new computing techno-
logy for Professional Excellence and Research.
PEO 3: Graduates shall work productively exhibiting ethical qualities for the betterment of
Society
PEO 4: Graduates shall possess effective Leadership and Communication Skills to work
harmoniously with the team to achieve set goals
PSO 2. Professional Skills: Ability to apply standard practices and methods in software
project management and software development using suitable programming environments
to deliver quality product to the industry.
CO PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO
1 2 3 4 5 6 7 8 9 10 11 12 1 2
C122.1 3 3 2 1 - - - 1 2 1 - - 1
C122.2 3 2 1 2 2 1 1 1 2 - - 1 1
C122.3 3 3 2 2 2 1 1 1 3 - - 2
C122.4 3 3 2 1 2 1 1 - 1 1
C122.5 3 3 2 2 2 1 1 1 1 - - 2
I CSE-B
S.No Program List Proposed Date Actual Date
Write a program that asks the user for a weight 20/03/2023 20/03/2023
1 in kilograms and converts it to pounds. There
are 2.2 pounds in a kilograms
Write a program that asks the user to enter three 20/03/2023 20/03/2023
numbers (use three separate input statements).
2 Create variables called total and average that
hold the sum and average of the three numbers
and print out the values of total and average.
Write a program that uses a for loop to print the 20/03/2023 27/03/2023
3
numbers 8, 11, 14, 17, 20, . . . , 83, 86, 89.
Write a program that asks the user for their 27/03/2023 27/03/2023
name and how many times to print it. The
4 program should print out the user’s name the
specified number of times.
Use a for loop to print a triangle like the one 27/03/2023 03/04/2023
below.
Allow the user to specify how high the triangle
should be.
5
*
**
***
****
Generate a random number between 1 and 10. 27/03/2023 03/04/2023
Ask the user to guess the number and print a
6
message based on whether they get it right or
not.
Write a program that asks the user for two 03/04/2023 03/04/2023
numbers and prints Close if the numbers are
7 within .001 of each other and Not close
otherwise.
I CSE-C
S.No Program List Proposed Date Actual Date
Write a program that asks the user for a weight 17/03/2023 24/03/2023
1 in kilograms and converts it to pounds. There
are 2.2 pounds in a kilograms
2 Write a program that asks the user to enter three 17/03/2023 24/03/2023
numbers (use three separate input statements).
Create variables called total and average that
hold the sum and average of the three numbers
and print out the values of total and average.
Write a program that uses a for loop to print the 17/03/2023 24/03/2023
3
numbers 8, 11, 14, 17, 20, . . . , 83, 86, 89.
Write a program that asks the user for their 24/03/2023 31/03/2023
name and how many times to print it. The
4 program should print out the user’s name the
specified number of times.
Use a for loop to print a triangle like the one 24/03/2023 31/03/2023
below.
Allow the user to specify how high the triangle
should be.
5
*
**
***
****
Generate a random number between 1 and 10. 24/03/2023 31/03/2023
Ask the user to guess the number and print a
6
message based on whether they get it right or
not.
Write a program that asks the user for two 31/03/2023 21/04/2023
numbers and prints Close if the numbers are
7 within .001 of each other and Not close
otherwise.
2. Roll List
III-CSE-A
I CSE-B
S
Regd.No Student Name
No.
1 22U41A0553 ADARI SURYA
2 22U41A0554 AMBATI SYAMALA
3 22U41A0555 BADDIREDDI VENKATA SAI DURGA ADITYA
4 22U41A0556 BADITABOYINA SINDHU BHARGAVI LIKHITA
5 22U41A0557 BATHULA ALEKHYA
6 22U41A0558 BEHARA HARSHITHA PATNAIK
7 22U41A0559 BODETI VIGNESH
8 22U41A0560 CHINNI GOPALA KRISHNA
9 22U41A0561 CHINTA MADHAVA RAO
10 22U41A0562 DABBIRU GAYATRI KEERTHI
11 22U41A0563 DAMILI SUGUNA
12 22U41A0564 DEVADI AMRUTHA VARSHINI
13 22U41A0565 DOGGA CHARISHMA
14 22U41A0566 DOKALA VARDHAN SAHIT
15 22U41A0567 GANDEPALLI RAJESH
16 22U41A0568 GATTEM MOHANA SRIJA
17 22U41A0569 GOLAGANA LAKSHMI SAI KEERTHIKA
18 22U41A0570 GULLINKALA SRI MANIKYA
19 22U41A0571 GUNTURU SESHANKA MOULI
20 22U41A0572 KADIRI SRAVANI
21 22U41A0573 KAMIREDDY PRAVALLIKA
22 22U41A0574 KANDREGULA KAVYA SRI HARSHITHA
23 22U41A0575 KARRI LOKESH VASU
24 22U41A0576 KOLA GAYATHRI SATYASRI
25 22U41A0577 KOLIPAKA SOWJANYA
26 22U41A0578 KUDIPUDI RAJESH
27 22U41A0579 KUDUPUDI VAMSI NAGA SAI
28 22U41A0580 MALLAREDDY SANDHYA
29 22U41A0581 MANTRI YASWANTH
30 22U41A0582 MURALIDHAR PUSARLA
31 22U41A0583 NAKKA V P KAVYA SUDHA
32 22U41A0584 NALLALA GANNI LAXMI
33 22U41A0585 NOTLA VENKATAMMA
34 22U41A0586 PAPANI ANITHA
35 22U41A0587 POLAVARAPU JEEVAN KUMAR
36 22U41A0588 POOTHIREDDY KALYANI
37 22U41A0589 RAPETI AKHIL
38 22U41A0590 RAYAPUREDDY SAI VARSHINI
39 22U41A0591 REYYA NTHIN
40 22U41A0592 ROKKAM ADINARAYANA
41 22U41A0593 RUSHINGI GOWRISANKAR
42 22U41A0594 SHAIK AZHARUDDIN
43 22U41A0595 SHAIK SHARMILA
44 22U41A0596 SRIKAKULAM SAI KUMAR
45 22U41A0597 SUROJIT BARIK
46 22U41A0598 TEPPALA AKASH
47 22U41A0599 VANAM DINESH KUMAR
48 22U41A05A0 VEERLA DHAKSHAYANI
49 22U41A05A1 VISSARAPU SIVA SANKAR
50 22U41A05A2 YALALA SAGAR
I CSE-C
S
Regd.No Student Name
No.
1 22U41A05A3 AGGALA DEEPAK RAVI KIRAN
2 22U41A05A4 ALLU RAJESH
3 22U41A05A5 ALOK KUMAR PANDEY
4 22U41A05A6 BADDIREDDY TEJA
BUDDHARAJU SRI SAI LAKSHMI AK-
5 22U41A05A7 SHAYA
6 22U41A05A8 CHINTA HARI MANIKANTA REDDY
7 22U41A05A9 DADI MOKSHESWARI
8 22U41A05B0 DADI NAVYASREE LAXMI
9 22U41A05B1 DADI SHIVAJI
10 22U41A05B2 DASULA YASWANTH REDDY
11 22U41A05B3 DULAM HEMANTH
12 22U41A05B4 GUDAMSETTY HAJARATH
KANDALA LAXMI KRISHNA RAMA VI-
13 22U41A05B5 HARI
14 22U41A05B6 KARRI SEKHAR
15 22U41A05B7 KARU VIJAYA VARA SAI SRI
16 22U41A05B8 KOCHERA RAHUL
17 22U41A05B9 KODAMANCHILI JAI SRI
18 22U41A05C0 KOILADA CHARAN SURYA MANI DURGA
19 22U41A05C1 KOLAPARTHI JYOTSHNA
20 22U41A05C2 KOMMUNURI SAHAN
21 22U41A05C3 KOTYALA BHASKAR
22 22U41A05C4 KUDIPUDI SAI GANESH
23 22U41A05C5 KUNDRAPU KUSHWANTH
24 22U41A05C6 LENKA LOKESH
25 22U41A05C7 M SAMHITA
26 22U41A05C8 MALLA VINAY
27 22U41A05C9 MAMIDI MOUKTHIKA SATYA SREE
28 22U41A05D0 MARISETTY PAVALI
29 22U41A05D1 MATTA RISHITH
30 22U41A05D2 MUTTA MOULI
31 22U41A05D3 MYCHARLA GOWRI
32 22U41A05D4 NAGALA KOMAL AKHILESH
33 22U41A05D5 NAGULAPALLI SHANMUKAHA
34 22U41A05D6 PATIMEEDA BHARAT
35 22U41A05D7 PATNALA GIRISH
36 22U41A05D8 PILLI JAYANTH
37 22U41A05D9 RAVI PAVANI
38 22U41A05E0 ROHIT KUMAR EDKE
39 22U41A05E1 RUTTALA HARSHA VARDHAN
40 22U41A05E2 SAMPANGI SAIKUMAR
41 22U41A05E3 SARAGADAM ADARSH
42 22U41A05E4 SHAIK CHANDINI
43 22U41A05E5 SHAIK SAMEERA
44 22U41A05E6 SRAVANTHI PEDAGADI
45 22U41A05E7 TADDI ANIL KUMAR
46 22U41A05E8 THAMMY SHYAM CHAKRAVARTHI
47 22U41A05E9 THEPPALA CHAITANYA
48 22U41A05F0 THOTA GIRIVARDHAN
49 22U41A05F1 THOTA VINOD
50 22U41A05F2 KORUKONDA BHAGYA SRI
1. Programs & Output
1.Write a program that asks the user for a weight in kilograms and
converts it to pounds. There are 2.2 pounds in a kilogram.
Program:
kilograms=float(input("Enter Weight in Kilograms: "))
pounds=2.2*kilograms
print("Weight in Pounds: ",pounds)
output:
Enter Weight in Kilograms: 5
Weight in Pounds: 11.0
Program:
n1=int(input("Enter First Number: "))
n2=int(input("Enter Second Number: "))
n3=int(input("Enter Third Number: "))
total=n1+n2+n3
average=total/3
print("Total= ",total)
print("Average= ",average)
output:
Enter First Number: 5
Enter Second Number: 8
Enter Third Number: 9
Total= 22
Average= 7.333333333333333
Program:
for i in range(8,90,3):
print(i,end=" ")
output:
8
11
14
17
20
.
.
.
.
89
4.Write a program that asks the user for their name and
how many times to print it.
The program should print out the user’s name the specified number of
times.
Program:
name=input("Enter your Name: ")
n=int(input("Enter how many times you want to print: "))
for i in range(n):
print(name)
Output:
Enter your Name: python
Enter how many times you want to print: 5
python
python
python
python
python
Output:
Enter the height of the triangle: 4
*
**
***
****
6. Generate a random number between 1 and 10. Ask the user to guess the
number and print a message based on whether they get it right or not.
Program:
import random
n=random.randint(1,10)
usernumner=int(input("Enter a number between 1 to 10(inclusive): "))
if(n==usernumner):
print("Your Guess is Right")
else:
print("Your Guess is Wrong")
print("Random Number: ",n)
Output:
Enter a number between 1 to 10(inclusive): 4
Your Guess is Wrong
Random Number: 1
7. Write a program that asks the user for two numbers and prints Close if
the numbers are within .001 of each other and Not close otherwise.
Program:
from decimal import *
num1 = Decimal(input("Enter number 1 : "))
num2 = Decimal(input("Enter number 2 : "))
diff= abs(num1-num2)
if(diff<=0.001):
print("Close")
else:
print("Not Close")
Output:
Enter number 1 : 7
Enter number 2 : 8
Not Close
8. Write a program that asks the user to enter a word and prints out
whether that word contains any vowels.
Program:
word=input("Enter a Word: ")
vowel='aeiouAEIOU'
flag=0
for i in vowel:
if i in word:
flag=1
break
if flag==1:
print("Word Contain Vowel")
else:
print("Word not Contain Vowel")
Output:
Enter a Word: python
Word Contain Vowel
9.Write a program that asks the user to enter two strings of the same
length.
The program should then check to see if the strings are of the same length.
If they are not, the program should print an appropriate message and
exit.
If they are of the same length, the program should alternate the charac-
ters
of the two strings. For example, if the user enters abcde and ABCDE the
program should print out AaBbCcDdEe.
Program:
s1=input("Enter First String: ")
s2=input("Enter Second String: ")
if(len(s1)==len(s2)):
print("String are with same length")
result=''
for i in range(len(s1)):
result=result+(s2[i]+s1[i])
print(result)
else:
print("String are with different length")
Output:
Enter First String: python
Enter Second String: programming
String are with different length
10. Write a program that asks the user for a large integer and inserts
commas into it according to the standard American convention for com-
mas in large numbers. For instance, if the user enters 1000000, the output
should be 1,000,000.
Here, we have used the “{:,}” along with the format() function to add commas
every thousand places starting from left. This is introduced in Python3
and it automatically adds a comma.
Program:
number=int(input("Enter a Long Number: "))
print("{:,}".format(number))
Output:
Enter a Long Number: 46746875686
46,746,875,686
11. In algebraic expressions, the symbol for multiplication is often left out,
as in 3x+4y or 3(x+5). Computers prefer those expressions to include the
multiplication symbol, like 3*x+4*y or 3*(x+5). Write a program that asks
the user for an algebraic expression and then inserts multiplication sym-
bols where appropriate.
Program:
s=input("Enter algebraic expression: ")
l=list(s)
result=''
i=0
while(i<len(l)):
if l[i]=='(':
index=l.index(')')
s2=''.join(l[i:index+1])
result=result+'*'+s2
i=i+len(s2)
elif l[i].isalpha():
result=result+'*'+l[i]
i=i+1
else:
result=result+l[i]
i=i+1
print(result)
Output:
Enter algebraic expression: x+y=6
*x+*y=6
12.
Program:
import random
l=[]
for i in range(20):
l.append(random.randint(1,100))
print("List: ",l)
print("Average: ", round(sum(l)/len(l),2))
print("Largest Value in List: ",max(l))
print("Smallest Value in List: ",min(l))
l1=sorted(l)
print("Second Largest Value in List: ",l1[-2])
print("Smallest Value in List: ",l1[1])
count=0
for i in l:
if i%2==0:
count+=1
print("Number of Even Numbers in the list: ",count)
Output:
List: [93, 99, 95, 16, 63, 20, 17, 51, 85, 100, 93, 3, 70, 61, 61, 79, 36, 91, 19,
81]
Average: 61.65
Largest Value in List: 100
Smallest Value in List: 3
Second Largest Value in List: 99
Smallest Value in List: 16
Number of Even Numbers in the list: 5
13. Write a program that asks the user for an integer and creates a list
that
consists of the factors of that integer.
Program:
n=int(input("Enter a number: "))
l=[]
for i in range(1,n+1):
if(n%i==0):
l.append(i)
print(l)
Output:
Enter a number: 65
[1, 5, 13, 65]
14.Write a program that generates 100 random integers that are either 0
or 1.
Then find the longest run of zeros, the largest number of zeros in a row.
For instance, the longest run of zeros in [1,0,1,1,0,0,0,0,1,0,0] is 4.
Program:
import random
x=[]
for i in range(100):
x.append(random.randint(0,1))
maxzero=0
count=0
for i in range(len(x)):
if(x[i]==0):
count=count+1
if(i==len(x)-1):
if(count>maxzero):
maxzero=count
if(x[i]==1):
if(count>maxzero):
maxzero=count
count=0
print("Longest run of Zeros in a row is",maxzero)
Output:
Longest run of Zeros in a row is 6
15.
Write a program that removes any repeated items from a list so that each
item appears at most once. For instance, the list [1,1,2,3,4,3,0,0] would be-
come [1,2,3,4,0].
Program:
l=list(map(int,input("Enter the elements into list with duplication: ").split(',')))
s=[]
for i in l:
if i not in s:
s.append(i)
print(s)
Output:
Enter the elements into list with duplication:1,2,3,4,1,2
[1,2,3,4]
16.Write a program that asks the user to enter a length in feet.The pro-
gram should then give the user the option to convert from feet into inches,
yards, miles, millimeters, centimeters, meters, or kilometers. Say if the
user enters a 1, then the program converts to inches, if they enter a 2, then
the program converts to yards, etc. While this can be done with if state-
ments,it is much shorter with lists and
it is also easier to add new conversions if you use lists.
Program:
feet=int(input("Enter feet: "))
opt=int(input("enter choice 1:inches 2:yards 3:miles 4:millimeters 5:cen-
timeters 6:meters 7:kilometers --->"))
l=[round(feet*12,3),round(feet*0.333,3),round(feet*0.000189,3),round(feet*3
04.8,3),\
round(feet*30.48,3),round(feet*0.305,3),round(feet*0.000305,3)]
print(l[opt-1])
Output:
Enter feet: 5
\enter choice 1:inches
2:yards
3:miles
4:millimeters
5:centimeters
6:meters
7:kilometers
4
1524.0
17.Write a function called sum_digits that is given an integer num and re-
turns the sum of the digits of num.
Program:
def sum_digits(num):
sum=0
while(num>0):
sum=sum+num%10
num=num//10
return sum
x=int(input("Enter a number: "))
s=sum_digits(x)
print("Sum of digits: ",s)
Output:
Enter a number: 8759
Sum of digits: 29
18.Write a function called first_diff that is given two strings and returns
the first location in which the strings differ.If the strings are identical, it
should return -1.
Program:
def first_diff(s1,s2):
if(s1==s2):
return -1
else:
if len(s1)==len(s2):
for i in range(len(s1)):
if s1[i]!=s2[i]:
return (i+1)
Output:
Enter string 1: python
Enter string 2: python
strings are identical
Program:
def number_of_factors(n):
fact_count=0
for i in range(1,n+1):
if(n%i==0):
fact_count+=1
return fact_count
n=int(input("Enter an integer: "))
x=number_of_factors(n)
print("factors count is",x)
Output:
Enter an integer: 5
factors count is 2
Enter an integer: 8
factors count is 4
20.Write a function called is_sorted that is given a list and returns True if
the list is sorted and False otherwise.
Program:
def is_sorted(l):
x=l[:]
x.sort()
if l==x:
return True
else:
return False
l=list(input("Enter list items : ").split())
print(is_sorted(l))
Output:
Enter list items : 5 7 6 9 8
False
21. Write a function called root that is given a number x and an integer n
and
returns x1/n. In the function definition, set the default value of n to 2.
Program:
def root(x,n=2):
return (x**(1/n))
x=int(input("Enter 'x' value: "))
n=int(input("Enter 'n' value: "))
ans1=root(x,n)
ans2=root(x)
print("Root value with n value: ",ans1)
print("Root Value with out n value (Default 2): ",ans2)
Output:
Enter 'x' value: 2
Enter 'n' value: 2
Root value with n value: 1.4142135623730951
Root Value with out n value (Default 2): 1.4142135623730951
22.
Write a function called primes that is given a number n and returns a
list of the first n primes. Let the default value of n be 100.
def primes(n=100):
l=[]
x=2
while(len(l)<n):
for i in range(2,int(x**0.5)+1):
if(x%i==0):
break
else:
l.append(x)
x=x+1
return l
n=int(input("Enter no of primes wanted: "))
print("List of first",n,"primes:",primes(n))
print("List of first '100' primes:",primes())
output:
Enter no of primes wanted: 10
List of first 10 primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
List of first '100' primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,
139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223,
227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307,
311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487,
491, 499, 503, 509, 521, 523, 541]
23.
Write a function called merge that takes two already sorted lists of
possibly different lengths, and merges them into a single sorted list.
(a) Do this using the sort method.
(b) Do this without using the sort method.
Program:
def merge(l1,l2):
s1=len(l1)
s2=len(l2)
l=[]
i,j=0,0
while i<s1 and j<s2:
if l1[i]<l2[j]:
l.append(l1[i])
i+=1
else:
l.append(l2[j])
j+=1
return (l+l1[i:]+l2[j:])
a=list(map(int,input("Enter sotred list 1: ").split()))
b=list(map(int,input("Enter sotred list 2: ").split()))
print("sorted list after merging:",merge(a,b))
output:
Enter sotred list 1: 1 3 5
Enter sotred list 2: 3 4 5
sorted list after merging: [1, 3, 3, 4, 5, 5]
24.
Write a program that asks the user for a word and finds all the
smaller words that can be made from the letters of that word.
The number of occurrences of a letter in a smaller word can’t
exceed the number of occurrences of the letter in the user’s word.
Program:
from itertools import permutations
s=input("Enter a word: ")
for i in range(2,len(s)):
for p in permutations(s,i):
print(''.join(p),end=' ')
output:
Enter a word: tac
ta tc at ac ct ca
25.
Write a program that reads a file consisting of email addresses,
each on its own line.
Your program should print out a string consisting of those email ad-
dresses
separated by semicolons.
'''
output:
1.file.txt 2.
[email protected] [email protected],[email protected]
[email protected]
26.
Write a program that reads a list of temperatures from a file called temp-
s.txt,
converts those temperatures to Fahrenheit, and writes the results to a file
called ftemps.txt.
'''
file1 = open('temps.txt', 'r')
lines = file1.readlines()
file2 = open('ftemps.txt', 'w')
for i in range(len(lines)):
c=lines[i].strip()
f=round((float(c)*1.8)+32,2)
file2.write(str(f)+"\n")
file2.close()
Output:
temps.txt ftemps.txt
10 10.8
20 20.6
30 30.5
27.
Write a class called Product. The class should have fields called name,
amount, and price, holding the product’s name, the number of items of
that product in stock, and the regular price of the product.
There should be a method get_price that receives the number of
items to be bought and returns a the cost of buying that many items,
where the regular price is charged for orders of less than 10 items,
a 10% discount is applied for orders of between 10 and 99 items, and
a 20% discount is applied for orders of 100 or more items.
There should also be a method called make_purchase that receives the
number of items to be bought and decreases amount by that much.
Program:
class product:
def __init__(self,name,items,price):
self.name=name;
self.items=items
self.price=price
def getprice(self,n):
if n<10:
print("Regular price is charged for you orders")
cost=n*self.price
print("If you place above 9 items you get 10% discount")
print("If you place above 99 items you get 20% discount")
elif n>=10 and n<100:
print("10% dicount is applied for you orders")
cost=n*self.price
discount=(cost*10)/100
finalcost=cost-discount
print("Actual Cost: ",cost)
print("10% Discount: ",finalcost)
print("Cost after 10% discount: ",discount)
print("If you place above 99 items you get 20% discount")
else:
print("20% dicount is applied for you orders")
cost=n*self.price
discount=(cost*20)/100
finalcost=cost-discount
print("Actual Cost: ",cost)
print("20% Discount: ",discount)
print("Cost after 20% discount: ",finalcost)
def my_purchase(self,n):
if n<10:
print("Regular price is charged for you orders")
cost=n*self.price
print("Final cost:",cost)
elif (n>=10) and (n<100):
print("10% dicount is applied for you orders")
cost=n*self.price
discount=(cost*10)/100
finalcost=cost-discount
print("Actual Cost: ",cost)
print("10% Discount: ",discount)
print("Final Cost after 10% discount: ",finalcost)
else:
print("20% dicount is applied for you orders")
cost=n*self.price
discount=(cost*20)/100
finalcost=cost-discount
print("Actual Cost: ",cost)
print("20% Discount: ",discount)
print("Final Cost after 20% discount: ",finalcost)
p=product("PEN",200,5)
n=int(input("Enter Number of pens you want to buy:"))
p.getprice(n)
n=int(input("Enter Number of pens you want to buy:"))
p.my_purchase(n)
output:
Enter Number of pens you want to buy:10
10% dicount is applied for you orders
Actual Cost: 50
10% Discount: 45.0
Cost after 10% discount: 5.0
If you place above 99 items you get 20% discount
28.
Write a class called Time whose only field is a time in seconds.
It should have a method called convert_to_minutes that returns a string of
minutes and seconds formatted as in the following example:
if seconds is 230, the method should return '5:50'.
It should also have a method called convert_to_hours that returns a string
of hours, minutes, and seconds formatted analogously to the previous
method.
class Time:
def __init__(self,sec):
self.sec=sec
def convert_to_minutes(self):
n=self.sec
minutes=n//60
seconds=n%60
return(str(minutes)+":"+str(seconds))
def convert_to_hours(self):
n=self.sec
hours=n//3600
minutes=(n//60)%60
seconds=n%60
return(str(hours)+":"+str(minutes)+":"+str(seconds))
a=int(input("Enter seconds: "))
c=Time(a)
print("Time in minutes:seconds format --->",c.convert_to_minutes())
print("Time in hours:minutes:seconds format --->",c.convert_to_hours())
Output:
Enter seconds: 12
Time in minutes:seconds format ---> 0:12
Time in hours:minutes:seconds format ---> 0:0:12
29.
Write a class called Converter. The user will pass a length and a unit
when declaring an object from the class—for example,
c = Converter(9,'inches'). The possible units are inches, feet, yards, miles,
kilometers, meters, centimeters, and millimeters.
For each of these units there should be a method that returns the
length converted into those units. For example, using the Converter
object created above, the user could call c.feet() and should get 0.75 as
the result.
Program:
class Converter:
def __init__(self,length,unit):
self.length=length
self.unit=unit
def feet(self):
if(self.unit=='feet'):
return self.length
elif(self.unit=='inches'):
return self.length/12
elif(self.unit=='yards'):
return self.length/0.333
elif(self.unit=='miles'):
return self.length/0.000189
elif(self.unit=='millimeters'):
return self.length/304.8
elif(self.unit=='centimeters'):
return self.length/30.48
elif(self.unit=='meters'):
return self.length/0.305
elif(self.unit=='kilometers'):
return self.length/0.000305
def inches(self):
if(self.unit=='feet'):
return self.length*12
elif(self.unit=='inches'):
return self.length
elif(self.unit=='yards'):
return self.length*36
elif(self.unit=='miles'):
return self.length*63360
elif(self.unit=='millimeters'):
return self.length*0.0393701
elif(self.unit=='centimeters'):
return self.length*0.393701
elif(self.unit=='meters'):
return self.length*39.3701
elif(self.unit=='kilometers'):
return self.length*39370.1
def yards(self):
if(self.unit=='feet'):
return self.length*0.333333
elif(self.unit=='inches'):
return self.length*0.0277778
elif(self.unit=='yards'):
return self.length
elif(self.unit=='miles'):
return self.length*1760
elif(self.unit=='millimeters'):
return self.length*0.00109361
elif(self.unit=='centimeters'):
return self.length*0.0109361
elif(self.unit=='meters'):
return self.length*1.09361
elif(self.unit=='kilometers'):
return self.length*1093.61
def miles(self):
if(self.unit=='feet'):
return self.length*0.000189394
elif(self.unit=='inches'):
return self.length*63360
elif(self.unit=='yards'):
return self.length*0.027777728
elif(self.unit=='miles'):
return self.length
elif(self.unit=='millimeters'):
return self.length/1609344
elif(self.unit=='centimeters'):
return self.length/160934.4
elif(self.unit=='meters'):
return self.length/1609.344
elif(self.unit=='kilometers'):
return self.length/1.609
def kilometers(self):
if(self.unit=='feet'):
return self.length/3280.84
elif(self.unit=='inches'):
return self.length/39370.1
elif(self.unit=='yards'):
return self.length/1093.61
elif(self.unit=='miles'):
return self.length/0.621371
elif(self.unit=='millimeters'):
return self.length/1000000
elif(self.unit=='centimeters'):
return self.length/100000
elif(self.unit=='meters'):
return self.length/1000
elif(self.unit=='kilometers'):
return self.length
def meters(self):
if(self.unit=='feet'):
return self.length/3.28084
elif(self.unit=='inches'):
return self.length/39.3701
elif(self.unit=='yards'):
return self.length/1.09361
elif(self.unit=='miles'):
return self.length/0.000621371
elif(self.unit=='millimeters'):
return self.length/1000
elif(self.unit=='centimeters'):
return self.length/100
elif(self.unit=='meters'):
return self.length
elif(self.unit=='kilometers'):
return self.length/0.001
def centimeters(self):
if(self.unit=='feet'):
return self.length/0.0328084
elif(self.unit=='inches'):
return self.length/0.393701
elif(self.unit=='yards'):
return self.length/0.0109361
elif(self.unit=='miles'):
return self.length*160934
elif(self.unit=='millimeters'):
return self.length/10
elif(self.unit=='centimeters'):
return self.length
elif(self.unit=='meters'):
return self.length*100
elif(self.unit=='kilometers'):
return self.length*100000
def millimeters(self):
if(self.unit=='feet'):
return self.length*304.8
elif(self.unit=='inches'):
return self.length/0.0393701
elif(self.unit=='yards'):
return self.length/0.00109361
elif(self.unit=='miles'):
return self.length*1609340
elif(self.unit=='millimeters'):
return self.length
elif(self.unit=='centimeters'):
return self.length*10
elif(self.unit=='meters'):
return self.length*100
elif(self.unit=='kilometers'):
return self.length*1000000
33.
Write a program to demonstrate Try/except/else.
try:
a=int(input("Enter 'a' value: "))
b=int(input("Enter 'b' value: "))
c=a//b
except ZeroDivisionError:
print("Division can't possible (b=0)")
else:
print(" a//b Value:",c)
Output:
Enter 'a' value: 0
Enter 'b' value: 10
a//b Value: 0
34.a.
Write a program to demonstrate try/finally and with/as.
Program:
try:
a=int(input("Enter 'a' value: "))
b=int(input("Enter 'b' value: "))
c=a//b
except ZeroDivisionError:
print("Division can't possible (b=0)")
else:
print(" a//b Value:",c)
finally:
print("End of the program")
Output:
Enter 'a' value: 10
Enter 'b' value: 2
a//b Value: 5
End of the program
34.b.
with statement in Python is used in exception handling to make the code
cleaner and much more readable.
It simplifies the management of common resources like file streams.
Additional Programs:
1. Write a python class to implement employee details and display using objects
Program:
Class Employee:
def __init__(self,name,id,department,job_title):
self.name=name
self.id=id
self.department=department
sef.job_title=job_title
def display_employee(self):
print(“name:”,self.name)
print(“ID:”,self.id)
print(“Department:”,self.department)
print(“job Title:”,self.job.title)
emp1=Employee(“Computer”,1234,”CSE”,”Developer”)
emp2=Employee(“Keyboard”,5678,”CSE”,”Tester”)
emp1.display_employee()
emp2.display_employee()
Output:
Name:Computer
ID:1234
Department:CSE
Job Title:Developer
Name:keyboard
ID:5678
Department:CSE
Job Title:Tester