0% found this document useful (0 votes)
5 views49 pages

Final R23 Python Student Lab Manual

The document is a student lab manual for the Python Programming Lab at KKR & KSR Institute of Technology and Sciences, detailing course objectives, outcomes, and various programming experiments. It outlines the institution's vision and mission, along with the department's educational objectives and program outcomes. The manual includes a comprehensive index of experiments ranging from basic input/output to advanced programming concepts and applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views49 pages

Final R23 Python Student Lab Manual

The document is a student lab manual for the Python Programming Lab at KKR & KSR Institute of Technology and Sciences, detailing course objectives, outcomes, and various programming experiments. It outlines the institution's vision and mission, along with the department's educational objectives and program outcomes. The manual includes a comprehensive index of experiments ranging from basic input/output to advanced programming concepts and applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES

Autonomous

Department of Computer Science & Engineering


STUDENT LAB MANUAL

R23

PYTHON PROGRAMMING LAB


[II [Link], II -SEM]

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

Dept. of CSE, Python Programming Lab Page 1


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
INDEX

Dept. of CSE, Python Programming Lab Page 2


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
Page
[Link] Contents No

1 Institute Vision & Mission 6

2 Department Vision & Mission 6

3 Program Educational Objectives & Program Outcomes 7-8

4 Program Specific Outcomes 9

5 Course Objectives & Outcomes 10

6 Course Mapping 11-12

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

Dept. of CSE, Python Programming Lab Page 3


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
otherwise.
Implement a program that asks the user to enter a word and prints 21
15
out whether that word contains any vowels.

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.

22 Write a function called sum_digits that is given an integer num and 28


returns the sum of the digits of num.
Write a function called first_diff that is given two strings and returns 29
23 the first location in which the strings differ. If the strings are identical,
it should return -1.

24 Write a function called number_of_factors that takes an integer and 30

Dept. of CSE, Python Programming Lab Page 4


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
returns how many factors the number has.
Write a function called is_sorted that is given a list and returns True if 31
25
the list is sorted and False otherwise.

Write a function called root that is given a number x and an integer n 32


26 and returns x1/n. In the function definition, set the default value of n
to 2.

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 program that reads a file consisting of email addresses, each on 35


29 its own line. Your program should print out a string consisting of those
email addresses separated by semicolons.
Write a program that reads a list of temperatures from a file called 36
30 [Link], converts those temperatures to Fahrenheit, and writes the
results to a file called [Link].

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.

33 Write a Python class to implement pow(x, n). 39

Dept. of CSE, Python Programming Lab Page 5


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
34 Write a Python class to reverse a string word by word. 40

35 Write a program to demonstrate Try/except/else 41

Write a function nearly_equal to test whether two strings are nearly 43


36 equal. Two strings a and b are nearly equal when a can be generated
by single mutation of b.

37 Write a python program to create wheel using turtle graphics 44

38 Write a python program on GUI to create a Registration form. 45

Write a python program to check whether a string starts and ends 45


39
with the same character or not (using Regular Expression re module).

Vision of the Institution

To become a knowledge centre for technical education and also to become the top engineering

Dept. of CSE, Python Programming Lab Page 6


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
college in the sunrise state of Andhra Pradesh.

Mission of the Institution

1. To incorporate benchmarked teaching and learning pedagogies in curriculum.


2. To ensure all round development of students through judicious blend of curricular, co-
curricular and extra-curricular activities.
3. To support cross-cultural exchange of knowledge between industry and academy.
4. To provide higher/continued education and research opportunities to the employees of the
institution.

Department of Computer Science and Engineering

Vision of the Department:

To commit itself to continuously improve its educational environment in order to develop


graduates with the strong academic and technical backgrounds needed to achieve distinction and
discipline.

Mission of the Department:

To provide a strong theoretical and practical education in a congenial environment so as to enable


the students to fulfill their educational and industrial needs.

Dept. of CSE, Python Programming Lab Page 7


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
Program Educational Objectives

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

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.

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.

3. Design/development of solutions: Design solutions for complex engineering problems and


design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

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.

Dept. of CSE, Python Programming Lab Page 8


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.

7. Environment and sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

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.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

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

projects and in multidisciplinary environments.

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.

Program Specific Outcomes

Dept. of CSE, Python Programming Lab Page 9


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
PSO1 (Engineering Fundamentals):

To provide students with a strong foundation in the mathematical, scientific and engineering

fundamentals in computer engineering.

PSO2 (Life-Long Learning):

To create awareness about life-long learning needed for successful professional career.

PSO3 (Managerial skills):

To familiarize the students with the analysis, design and implementation of software and to inculcate
team management skills with cross-cultural, promoting knowledge.

PSO4 (Career Development):

To motivate the graduates to work with professionals in the fields related to computing applications using
hardware and software integration.

PSO5 (Social context):

To excel in posing great challenges in socio economic and managerial environments to become successful
trend setter.

Dept. of CSE, Python Programming Lab Page 10


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
Course Objectives:

C129.1: To acquire programming skills in core Python


C129.2: To acquire Object Oriented Skills in Python.
C129.3: To develop the skill of designing Graphical user Interfaces in Python.
C129.4: To develop the ability to write database applications in Python.
C129.5: To develop modules and packages.

Course Out Comes:

Course Code Course Outcome Taxonomy Level

C129.1 Write, Test and Debug Python Programs TL3: Application

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

C129.4 Use various applications using python TL3: Application

Signature of the Faculty Head of the Department of CSE

Dept. of CSE, Python Programming Lab Page 11


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

Mapping of Course Outcomes with Program outcomes

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

1: Low 2:Moderate 3:High

Mapping Of Course Outcomes with PSO'S

CO/PSO PSO1 PSO2 PSO3

C129.1 1

C129.2 1

C129.3 1

C129.4 2

1: Low 2:Moderate 3:High

Mapping Of Experiments with COS

EXP/CO C129.1 C129.2 C129.3 C129.4


E1 3
E2 3
E3 3 3
E4 3 3
E5 3 3
E6 3 3
E7 3 3
E8 3 3
E9 3 3
E10 3 3
E11 3 3
E12 3 3 3
E13 3 3 3

Dept. of CSE, Python Programming Lab Page 12


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
E14 3 3 3
E15 3 3 3
E16 3 3 3
E17 3 3 3
E18 3 3 3
E19 3 3 3
E20 3 3 3
E21 3 3 3
E22 3 3 3
E23 3 3 3
E24 3 3 3
E25 3 3 3
E26 3 3 3
E27 3 3 3
E28 3 3 3
E29 3 3 3
E30 3 3 3
E31 3 3 3
E32 3 3 3
E33 3 3 3
1: Low 2:Moderate 3:High

Dept. of CSE, Python Programming Lab Page 13


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

INTRODUCTION ABOUT LAB


There are 70 systems DELL Systems and Windows 7 installed in the Lab. Their configurations are
as follows:

System : DELL

Processor : Intel(R)Core(TM)i5 7400 CPU@3.00GHz

RAM : 8 GB

Hard Disk : 1TB

Mouse : Optical Mouse

Network Interface card : Present

HARDWARE AND SOFTWARE REQUIRED:

[Link] systems are configured in Windows 7.

[Link] installed: Python 3.7

[Link] are provided for the student in the 1:1 ratio.

[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.

 Lab records need to be submitted on or before date of submission.

Dept. of CSE, Python Programming Lab Page 14


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
[Link] a program that asks the user for a weight in kilograms and converts it to pounds. There
are 2.2 pounds in a kilogram.
Request: Program that asks the user for a weight in kilograms and converts it to pounds.
Analysis: Determine what information the user will have to provide.
Enter the weight in kilograms: 5
Weight in Pounds: 11.00
Design:
 Input weight in kilograms
 Convert the weight in kilograms into pounds using the formula
Pounds=2.2*kgs
 Print the weight in pounds.
Testing:

Dept. of CSE, Python Programming Lab Page 15


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 16


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
3. Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, . . . , 83, 86, 89
Request: Program that uses a for loop to print the numbers 8, 11, 14, 17, 20, . . . , 83, 86, 89
Analysis: Determine what information the user will have to provide.
Use for loop to print that sequence. The syntax of for loop is as follows:
Syntax: for var in range(start,,end,step):
statement
Enter Range: 20
8,11,14,17
Design:

 Read n value.
 Use for loop with range function to generate that sequence
for i in range(8,n,3):
print i
Testing:

Dept. of CSE, Python Programming Lab Page 17


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
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.
Request: 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.
Analysis: Determine what information the user will have to provide.
Use for loop to print that name. The syntax of for loop is as follows:
Syntax: for var in range(start,,end,step):
Statement
Enter name: KITS
Enter How many times to print: 3
KITS
KITS
KITS
Design:
 Read name.
 Read n value to print how many no. of times to print name
 Use for loop with range function to generate that sequence
for i in range(n):
print name
Testing:

Dept. of CSE, Python Programming Lab Page 18


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 19


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 20


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 21


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 22


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 23


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 24


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 25


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Enter a String kkr & ksr institute of technology and sciences


Dictionary after spliting
{0: 'kkr', 1: '&', 2: 'ksr', 3: 'institute', 4: 'of', 5: 'technology', 6: 'and', 7: 'sciences'}
String after join with -
kkr-&-ksr-institute-of-technology-and-sciences

Dept. of CSE, Python Programming Lab Page 26


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 27


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 28


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 29


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 30


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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

Dept. of CSE, Python Programming Lab Page 31


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
 return count

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:

Dept. of CSE, Python Programming Lab Page 32


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 33


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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:

Dept. of CSE, Python Programming Lab Page 34


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
 Input two list of elements which are in sorted order.
 Apply the sort function which is predefined in python for merging the two sorted lists.
 Make the two sorted list as a single list.
 Apply manual sorting process without using predefined function
 Merge the two lists in another list.
 Output the sorted list with using sort function.
 Output the sorted list that is generated without using sotr function.

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

Dept. of CSE, Python Programming Lab Page 35


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
 Output the smaller word.
Testing:

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.

Dept. of CSE, Python Programming Lab Page 36


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
Testing:

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]

Dept. of CSE, Python Programming Lab Page 37


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
 Print Program done Successfully
 close [Link], [Link] files
Testing:

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:

Dept. of CSE, Python Programming Lab Page 39


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
 Construct A Class Time Containing Functions Conver_to_minutes() and
Convert_to_hours()
 Take the input Time in seconds.
 Convert seconds to minutes using Convert_to_minutes() method
 Convert seconds to hours using Convert_tohours() method
 Display two outputs in newlines
Testing:

26. Write a Python class to implement pow(x, n)


Request: Program to implement class contains pow() function.
Analysis: Determine what information the user will have to provide
Enter Base Value:2
Enter power Value:-3
0.125
Design:
 Construct Class with Power()
 Take Base value as first input
 Take Power value as Second input
 Calculate Value using Pow() method in Class
Dept. of CSE, Python Programming Lab Page 40
KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
 Display Output

Testing:

27. Write a Python class to reverse a string word by word.


Request: Program to Implement class for reverse the string word by word.
Analysis: Determine what information the user will have to provide
Enter string: Ramanujam is great mathematician
majunamaR si taerg naicitamehtam
Design:
 Construct A class with Reverse logic
 Read the Input String
 Reverse the function using reverse_word() method in class
 Display Output
Dept. of CSE, Python Programming Lab Page 41
KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
Testing:

28. Write a program to demonstrate Try/except/else.


Request: Write a program to demonstrate Try/except/else.
Analysis:
Execute try and else blocks. The code should contain cases that execute both try and except
conditions. The output for the below code is as follows.
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError'> occurred.
Next entry.

Dept. of CSE, Python Programming Lab Page 42


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
The entry is 2
The reciprocal of 2 is 0.5
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError'> occurred.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
Design:
 Input a list containing different types of data
 Now check for different types of exceptions using except block
 Also print types of exceptions as a next step
 Now, apply try-else block for reciprocal of even numbers
 try block is used for checking whether given number is even or not
 If it is raises exception except clause raises an exception and print not an even number
otherwise else block will be executed and print reciprocal of even number
Testing:

Dept. of CSE, Python Programming Lab Page 43


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

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

Dept. of CSE, Python Programming Lab Page 44


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

OUTPUT:

Enter first string::


RISE
Enter second string::
RISEE
Strings are nearly equal.

30. Write a python program to create wheel using turtle graphics.

Request: program to create spiral circle using turtle.


Analysis: “Turtle” is a python feature like a drawing board, which lets you command a turtle to
draw all over it. You can use functions like [Link]() and [Link]() which can move the
turtle around.
Design:
Step 1: import turtle ,itertools modules.
Step 2:create colors list.
Colors=[‘red’,’green’,’blue’,’yellow’,’magenta’]
Step 3:create cycle for colors.
Colors=cycle(colors)
Step 4:create turtle object
t=turtle()
Step 5: set speed of drawing
[Link](0)
Step 6: repeat the steps for _ in range(37)
[Link](next(colors))[sets the color]
[Link](50)[draw a circle with radius of 50]
[Link](20)[moves 20 degrees angle towards left in counter clock wise]

Output:
Dept. of CSE, Python Programming Lab Page 45
KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

31) Write a python program on GUI to create a Registration form

Request: Use tkinter tool to develop gui application

Design: Use Labels , Check buttons and radio buttons.

32) Write a python program to check whether a string starts and ends with the same character or not
(using Regular Expression re module).

Request: Input a String

Design: use re module and create a regular expression as r'^[a-z]$|^([a-z]).*\1$'

Apply search function on your string with regular expression

Output:

Dept. of CSE, Python Programming Lab Page 46


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
The string is:
abcbabda
The given string starts and ends with the same character

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?

Dept. of CSE, Python Programming Lab Page 47


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous
23. What is pickling and unpickling?
24. How memory is managed in Python?
25. What are the tools that help to find bugs or perform static analysis?
26. What is negative index in Python?
27. What is module and package in Python?
28. Mention what are the rules for local and global variables in Python?
29. How can you share global variables across modules?
30. Explain how to delete a file in Python?
31. Explain how can you generate random numbers in Python?
32. Explain what is Flask & its benefits?
33. Mention what is the difference between Django, Pyramid, and Flask?
34. Explain what is the common way for the Flask script to work?
35. Explain Python's zip() function.?
36. Explain Python's pass by references Vs pass by value . (or) Explain about Python's
parameter passing mechanism?
37. Explain how to overload constructors or methods in Python.
38. Name the File-related modules in Python?
39. Explain the use of with statement?
40. Explain all the file processing modes supported by Python ?
41. Explain how to redirect the output of a python script from standout(ie., monitor) on to a file
?
42. How do you create a dictionary which can preserve the order of pairs?
43. When does a dictionary is used instead of a list?
44. What is the use of enumerate() in Python?
45. How many kinds of sequences are supported by Python? What are they?
46. Name few methods for matching and searching the occurrences of a pattern in a given text
String ?
47. Explain split(), sub(), subn() methods of
48. Name few Python modules for Statistical, Numerical and scientific computations ?
49. What is TkInter?
50. Is Python object oriented? what is object oriented programming?
51. Name and explain the three magic methods of Python that are used in the construction and
initialization of custom Objects.
52. What is a Class? How do you create it in Python?
53. What are Exception Handling? How do you achieve it in Python?
54. Explain Inheritance in Python with an example.
55. What is multithreading? Give an example.
56. How instance variables are different from class variables?
57. How is Inheritance and Overriding methods are related?
58. Which methods of Python are used to determine the type of instance and inheritance?
59. Does Python supports interfaces like in Java? Discuss.
60. What are Accessors, mutators, @property?
61. Differentiate between .py and .pyc files?
62. How would you define a protected member in a Python class?
63. Name few Python Web Frameworks for developing web applications?

Dept. of CSE, Python Programming Lab Page 48


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
Autonomous

Dept. of CSE, Python Programming Lab Page 49

You might also like