Final R23 Python Student Lab Manual
Final R23 Python Student Lab Manual
Autonomous
R23
Autonomous
KKR & KSR INSTITUTE OF TECHNOLOGY
AND
SCIENCES
Vinjanampadu, Guntur District – 522 017 (A. P.)
Date of Compiled by Authorized by
Document NO: Issue: [Link]
PROF & HOD
KITS/CSE/LAB [Link] CSE
MANUAL/PPSUC Date of Verified by
LAB revision
7 Introduction to Lab 13
Experiments
Implement a program that asks the user for a weight in kilograms and 14
8
converts it to pounds. There are 2.2 pounds in a kilogram.
Implement a program that asks the user to enter three numbers (use 15
three separate input statements). Create variables called total and
9
average that hold the sum and average of the three numbers and
print out the values of total and average.
10 Develop program that uses a for loop to print the numbers 8, 11, 14, 16
17, 20, . . . , 83, 86, 89.
Implement a program that asks the user for their name and how many 17
11 times to print it. The program should print out the user’s name the
specified number of times.
Use a for loop to print a triangle like the one below. Allow the user to 18
specify how high the triangle should be.
*
12 **
***
****
Generate a random number between 1 and 10. Ask the user to guess 19
13 the number and print a message based on whether they get it right or
not.
14 Implement a program that asks the user for two numbers and prints 20
Close if the numbers are within .001 of each other and Not close
Develop program that asks the user to enter two strings of the same 22
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
16
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 abcde and ABCDE the program should print out AaBbCcDdEe.
Implement a program that asks the user for a large integer and inserts 23
17 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.
Implement a program that generates a list of 20 random numbers 24
between 1 and 100.
(a) Print the list.
18 (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.
Write a program to use split and join methods in the given string 25
19
and store them in a dictionary data structure.
Write a program that removes any repeated items from a list so that 26
20 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].
Write a program that asks the user to enter a length in feet. The 27
program should then give the user the option to convert from feet
into inches, yards, miles, millimeters, centimeters, meters, or
21 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.
Write a function called merge that takes two already sorted lists of 33
possibly different lengths, and merges them into a single sorted list.
27
(a) Do this using the sort method. (b) Do this without using the sort
method
Write a program that asks the user for a word and finds all the smaller 34
words that can be made from the letters of that word. The number of
28
occurrences of a letter in a smaller word can’t exceed the number of
occurrences of the letter in the user’s word.
Write a class called Product. The class should have fields called name, 37
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
31 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.
Write a class called Time whose only field is a time in seconds. It 38
should have a method called convert_to_minutes that returns a string
of minutes and seconds formatted as in the following example: if
32
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.
To become a knowledge centre for technical education and also to become the top engineering
1. To provide students with a strong foundation in areas like mathematics, science and engineering
fundamentals so as to enable them to solve and analyze engineering problems and prepare them
to graduate studies , R&D and studies of higher level .
2. To develop an ability to analyze and understand the requirements of software, technical
specifications required and provide novel engineering solutions to the problems associated with
hardware and software.
3. To provide exposure to cutting edge technologies to students thereby making them to achieve
excellence in the areas of their studies.
4. To provide adequate training to students to make them work in teams on multi disciplinary
projects with effective communications skills and leadership qualities
5. To prepare the students for a successful career wherein they strike a balance between ethical
values and commercial values.
PROGRAM OUTCOMES
2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
To provide students with a strong foundation in the mathematical, scientific and engineering
To create awareness about life-long learning needed for successful professional career.
To familiarize the students with the analysis, design and implementation of software and to inculcate
team management skills with cross-cultural, promoting knowledge.
To motivate the graduates to work with professionals in the fields related to computing applications using
hardware and software integration.
To excel in posing great challenges in socio economic and managerial environments to become successful
trend setter.
C129.2 Use Conditionals and Loops for Python Programs TL3: Application
C129.3 Use functions and represent Compound data using Lists, TL3: Application
Tuples and Dictionaries
CO/PO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
C129.1 3 3 3 3
C129.2 3 3 3 3
C129.3 3 3 3 3
C129.4 3 3 3 3
C129.1 1
C129.2 1
C129.3 1
C129.4 2
System : DELL
RAM : 8 GB
[Link] are assigned numbers and same system is allotted for students when they do the lab.
GUIDELINES TO STUDENTS
Equipment in the lab for the use of student community. Students need to maintain a proper
decorum in the computer lab. Students must use the equipment with care. Any damage is
caused is punishable.
Students are required to carry their observation / programs book and Record with
completed exercises while entering the lab.
Students are supposed to occupy the machines allotted to them and are not supposed to talk
or make noise in the lab. The allocation is put up on the lab notice board.
Lab can be used in free time / lunch hours by the students who need to use the systems
should take prior permission from the lab in-charge.
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.
Request: 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.
Analysis: Determine what information the user will have to provide.
Enter Number1: 45
Enter Number2: 34
Enter Number3: 12
Total: 91
Average: 30.333
Design:
Input three numbers.
Calculate total and average
Total=n1+n2+n3
Avg=total/3
Print total, avg
Testing:
Read n value.
Use for loop with range function to generate that sequence
for i in range(8,n,3):
print i
Testing:
5. Use a for loop to print a triangle like the one [Link] the user to specify how high the
triangle should be.
*
**
***
****
Request: Use a for loop to print a triangle like the one below. Allow the user to specity the height
of the triangle.
Analysis: Determine what information the user will have to provide.
Enter the highest of triangle:5
*
**
***
****
*****
Design:
Read the height of the triangle from the user.
Use a for loop for printing in given number of lines.
Use another loop inside it to print the stars in same row equal to the row number.
Testing:
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.
Request: Generate a random number between 1 and 10. Ask the user to guess the number and
print a message based on whether they it right or not.
Analysis: Determine what information the user will have to provide.
Guess a number between 1 and 10 until you get it right : 1
Guess a number between 1 and 10 until you get it right : 2
Guess a number between 1 and 10 until you get it right : 3
Guess a number between 1 and 10 until you get it right : 4
Guess a number between 1 and 10 until you get it right : 5
Guess a number between 1 and 10 until you get it right : 7
Guess a number between 1 and 10 until you get it right : 6
Well guessed!
Design:
Import random library.
Generate a random number between 1 and 10.
Use the while loop and ask the user to guess a number between 1 and 10.
Repeat until the user guesses the correct number.
Print that the user guessed the correct number.
Testing:
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.
Request: 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.
Analysis: Determine what information the user will have to provide.
Enter Number1:12
Enter Number2:13.001
Not Close
Design:
Import math library.
Input two numbers from the user.
Check if the difference between those values is less than .001 using the abs function.
If yes print Close otherwise print Not close.
Testing:
8. Write a program that asks the user to enter a word and prints out whether that word
contains any vowels.
Request: A program that asks the user to enter a word and prints out whether that word contains
any vowels.
Analysis: Determine what information the user will have to provide.
Enter word: Hello
Word contains vowels
Design:
Input a word from the user.
Place all the vowels in a set.
Using any function check if any of the letter in the word is present in the set.
Testing:
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 abcde and
ABCDE the program should print out AaBbCcDdEe.
Request: 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 abcde and ABCDE the
program should print out AaBbCcDdEe.
Analysis: Determine what information the user will have to provide.
Enter String1:hello
Enter String2:world
Checking Both Strings of same length
Yes, Both strings of same length
The result string is hweolrllod
Design:
Input two strings from the user.
Check length of the two strings is equal or not using len function.
If not equal print not equal and exit the program.
Otherwise print both strings are of same length.
Using a loop append each character from the strings to result string.
Print the output.
Testing:
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.
Request: To convert the largest integer into the american standards by inserting the commas.
Analysis: To determine the output based on the user requirement.
Enter Number:100000
100,000
Design:
To give the largest input from the user.
Deciding the format based on the American standards.
Print the formatted output.
Testing:
11. 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.
Request: To generate the random 20 numbers from 1 to 100 and performing the operations
listed by the user.
Analysis: To determine the output based on the user requirement.
Generating the random numbers.
a) [68, 56, 54, 97, 51, 57, 43, 61, 12, 4, 45, 83, 60, 5, 61, 79, 64, 90, 58, 70]
b)Average of list elements is= 55.9
c)Smallest value in the list is 4
Largest value in the list is 97
d)Second Smallest value in the list is 5
Second Largest value in the list is 90
Second Smallest value in the list is 5
Second Largest value in the list is 90
e)No. of Even numbers 10
Design:
Create an empty list to insert the random numbers.
Repeat a loop upto 20 times and generate the 20 random numbers into the empty list.
Find the average of the numbers in the list.
print the average
Generate the smallest value and the largest values in the list.
Print the smallest value and largest value of the list.
Generate the second smallest and second largest value
Print the second smallest and second largest.
Print the no of even numbers that are present in the list.
Testing:
12. Write a program to use split and join methods in the given string and store them in a dictionary data
structure
Request: To read a string
Analysis: Apply split and join methods on the input string
Output:
13. 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].
Request: 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].'''
l=eval(input("Enter list elements"))
Analysis:
Enter list elements[1,2,3,3,2,1]
The original list [1, 2, 3, 3, 2, 1]
List after removing duplicates [1, 2, 3]
Design:
Input list
Method 1:
Use unique() to get unique list of elements
Method 2:
take a new list
Iterate original list
if list element is not present in new list add to it else do nothing
Method 3:
Use list comprehension with the same logic as in method2
Finally print new list
Testing:
14. 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, millimetres, centi meters,
meters, or kilo meters. 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.
Request: 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, millimetres, centimetres, meters,
or kilometres. 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.
Analysis:
Enter length in feet:20
Enter which conversion inches
Length from feet to inches=240.0
Design:
Input length to be converted from user and also format of string type into which it should
be converted.
Store all formats of string type in a list named l1
Now store operation to be performed for each conversion in another list l2
Iterate l1 and find which matches to input format given by user and perform operation
corresponding to it through l2
Display converted measurement
Testing:
15. Write a function called sum_digits that is given an integer num and returns the sum of the
digits of num.
Request: Write a function called sum_digits that is given an integer num
and returns the sum of the digits of num.
Analysis:
Enter number:456
Sum of digits of given number 456 is 15
Design:
Input a number n
Initialize sum with 0
Iterate n until it becomes 0 with the 3 below operations done internally
extract digit from number n
add digit to sum variable
divide n with 10
Finally print sum
Testing:
16. Write a function called first_diff that is given two strings and returns the first location in
which the strings [Link] the strings are identical, it should return -1.
Request: Define a function called first_diff that is given two strings and returns the first location
in which the strings [Link] the strings are identical, it should return -1.
Analysis:
Enter String1:ABC
Enter String2:ABA
Strings are different at first location is
2
Design:
Input two strings s1 and s2
if length of two strings is same then perform the following steps
Iterate first string s1
if every character in both strings are same continue else break the loop and print the
location of first string
Testing:
17. Write a function called number_of_factors that takes an integer and returns
how many factors the number has.
REQUEST: Write a function called number_of_factors that takes an integer and returns how many
factors the number has.
ANALYSIS:
Enter any Number:6
11
22
33
64
[Link] factorrs are 4
Design:
Input a number n
call function no_ of_ factors()
print count
no_ of_ factors():
Initialise count with 0
Iterate number from 1 to n using variable i
if n is divisible by i then print i and count and then increment count by 1
18.) Write a function called is_sorted that is given a list and returns True if the list is sorted and
False otherwise.
Request: Program to check whether the list is sorted or not using a function called is_sorted().
Analysis: Determine what information the user will have to provide.
Enter list Elements: [1,2,3,4]
True
Design:
Input the list of elements.
Check for the elements order.
If the sorting order is satisfied then return True.
Otherwise return False.
Testing:
19.)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.
Request: Program to find root of number.
Analysis: Determine what information the user will have to provide.
Enter value x:2
Enter value n:2
The value of n root x is: 1.4142135623730951
Design:
Input the value of x and n
Process the requires operation by using ** operator.
Return the root value of x^1/n.
Testing:
20.) 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.
Request: Program to merge two sorted lists into a single sorted list by using
a.) sort function.
b.) no sort function.
Analysis: Determine what information the user will have to provide.
Enter sorted List1:[10,20,30,40]
Enter sorted List2:[50,70,100]
Merge list in sorted order: [10, 20, 30, 40, 50, 70, 100]
Merge list with using sort function: [10, 20, 30, 40, 50, 70, 100]
Design:
Testing:
21. 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.
Request: 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.
Analysis: Determine what information the user will have to provide.
Enter word: agree
gag
Design:
Open the text file which contains number of words.
Input a word of user choice.
Find the smaller word which that the given word which exist in the text file
22. 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.
Request: 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.
Analysis: Determine what information the user will have to provide
print the each email address separated with semicolons.
Design:
Input the file which contain email addresses.
separate each email address as a sting.
Print the email addresses separated with semicolons.
23. Write a program that reads a list of temperatures from a file called [Link], converts
those temperatures to Fahrenheit, and writes the results to a file called [Link].
Request: Program that reads a list of temperatures from a file called [Link], converts those
temperatures to Fahrenheit, and writes the results to a file called [Link].
Analysis: Determine what information the user will have to provide
Take the input from [Link] convert the temperature to Fahrenheit save it in [Link] file
Design:
Read the data in [Link] to dtemp
Create [Link] to save the output
Read each temperature in dtemps.
Convert Temperature to Fahrenheit by using formula f=t*(9/5)+32
Write this output into file [Link]
24. 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.
Request: Program Contain a Class called Product. The class should have Three fields Contain
Product Details and Functions to manage the Product selling.
Analysis: Determine what information the user will have to provide
Enter product name: Bread
Enter no. of items for that product in stock:10
Dept. of CSE, Python Programming Lab Page 38
KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
Enter price of regular product:30
Enter no. of items to buy 2
Final costs: 60.
Remaining stock is : 8
Design:
Construct the class Contain the Fields of Product and functionalities of Product
Take the Initial Product Details Like name, no. of items and price using Costructor.
Take input from customer how many items he/she wants
Calculate the Price and Display
Display Remaining Stock Details
Testing:
25. 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.
Request: Program that Contain a Class called Time Contain a Functions for converting seconds to
minutes and seconds to hours.
Analysis: Determine what information the user will have to provide
Enter time in seconds:600
converted time to minutes and seconds= 10:00
converted time to hours and minutes= 00:10:00
Design:
Testing:
29 Write a function nearly _equal to test whether two strings are nearly equal. Two strings a and b are
nearly equal when a can be generated by a single mutation on b
Request: Read Two Strings
Analysis: Compare two Strings both are nearly equal or not
Design:
count=0
i=j=0
while(i<len(str1) and j<len(str2)):
if(str1[i]!=str2[j]):
count=count+1
if(len(str1)>len(str2)):
i=i+1
elif(len(str1)==len(str2)):
pass
else:
i=i-1
if(count>1):
return False
i=i+1
j=j+1
if(count<2):
return True
OUTPUT:
Output:
Dept. of CSE, Python Programming Lab Page 45
KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
32) Write a python program to check whether a string starts and ends with the same character or not
(using Regular Expression re module).
Output:
Viva Questions
1. What is PEP8?
2. How do we interpret Python?
3. What is a Python decorator?
4. What is the difference between list and tuple?
5. What are Dict and List Comprehensions?
6. What is Lambda in Python?
7. What are iterators?
8. What is slicing?
9. What is docstring?
10. What is pass in Python?
11. Why do lambda forms in Python not have statements?
12. What is unittest?
13. What is the difference between Xrange and range?
14. How do you delete a file in Python?
15. What is the use of the split function in Python?
16. What is Python?
17. Name some of the features of Python.
18. What are the supported data types in Python?
19. What are Python's dictionaries?
20. What is the purpose of ** operator?
21. What is the purpose of ** operator?
22. What is Python? What are the benefits of using Python?