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

Lab Manual U18csi2201 Python Programming

The document is a laboratory manual for a Python Programming course at Kumaraguru College of Technology, detailing various exercises for students to implement Python programs. It covers topics such as basic arithmetic operations, Newton's laws, string manipulation, control statements, and user-defined functions. Each exercise includes objectives, syntax, and example solutions to guide students in their programming tasks.

Uploaded by

Dharun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views35 pages

Lab Manual U18csi2201 Python Programming

The document is a laboratory manual for a Python Programming course at Kumaraguru College of Technology, detailing various exercises for students to implement Python programs. It covers topics such as basic arithmetic operations, Newton's laws, string manipulation, control statements, and user-defined functions. Each exercise includes objectives, syntax, and example solutions to guide students in their programming tasks.

Uploaded by

Dharun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

KUMARAGURU COLLEGE OF TECHNOLOGY, COIMBATORE – 641 049

Department of Computer Science and Engineering

U18CSI2201 – Python Programming

Laboratory Manual

1|Page
Exercise 01

Course Code U18CSI2201


Course Python Programming
Course / Branch B.E – Common to all branches
Title Implement simple python programs using
interactive and script mode.

INTRODUCTION
OBJECTIVE OF THE EXERCISE
To perform the following exercises using Python
1. Python is also a calculator. Use python shell in interactive mode to find solutions for
the following questions
a. -9+20
b. 3.14+2.5*82.13
c. 4.7+2.3
d. n=16
n/6
n/6.0
n//6
2. Newton’s Second Law of motion is expressed as F = m × a, where F is force, m is mass
and a is acceleration. Write a program to calculate the acceleration if mass of an object
and the force on that object are given as input. Display the result to the user.
Test Case 1 2
Input Mass=5, Force =1050 Mass =3, Force=564
Output 210 188

3. Write a program that acts like a waiter for a Restaurant. The program should ask the
user for their name and how many people will be attending. The output should be
Hello, welcome to Happy Snacks. What name is your booking under?
Carly
Hi Carly! How many people will be attending?
4
Ok Carly, I will see if I can find a table for 4.

2|Page
4. The finance department of a company wants to calculate the monthly pay of one of its
employee. Monthly pay should be calculated as mentioned in the below formula and
display all the employee details.
Monthly pay=number of hours worked in a week*rate per hour*no.of weeks.

SOLUTION
1. >>> -9+20
11
>>> 3.14+2.5*82.13
208.46499999999997
>>> 4.7+2.3
7.0
>>> m=16
>>> n=16
>>> n/6
2.6666666666666665
>>> n/6.0
2.6666666666666665
>>> n//6
2>>>

2. m=50
>>> f=1050
>>> print(f/m)
21.0

3. print("Hello, welcome to Happy Snacks. What name is your booking under?")


name=input()
print("Hi ",name,"! How many people will be attending?")
count=int(input())
print("OK",name,", I will see if I can find a table for ",count)

4. code=input("Enter Employee Code ")


name=input("Enter name")
3|Page
rate=100
week=4
hours=int(input("Enter number of hours worked "))
pay=hours*rate*week
print("Monthly Pay ",pay)

4|Page
Exercise 02

Course Code U18CSI2201


Course Python Programming
Course / Branch B.E – Common to all branches
Title Develop python programs using id() and
type() functions

INTRODUCTION
OBJECTIVE OF THE EXERCISE
To perform the following exercises using Python
1. Identify the type of the following
a. -9+11
b. 5+7j
c. “Hello”
d. ‘Hi’
e. 3.4*5.6
f. True
2. Write a python code to swap two numbers without using a third variable and display
their id using id() before and after swap.

SYNTAX
Syntax – type()
type(identifier)

Syntax – id()
id(identifier)

SOLUTION
1. a=-9+20
print(type(a))
b=5+7j
print(type(b))
c="Hello"
print(type(c))
d='Hi'
5|Page
print(type(d))
e=3.14*5.6
print(type(e))
print(type(True))

2. a=int(input("Enter number 1"))


print(id(a))
b=int(input("Enter number 2"))
print(id(b))
a,b=b,a
print("After swap")
print("Number 1 ",a)
print("Number 2 ",b)
print(id(a))
print(id(b))

6|Page
Exercise 03

Course Code U18CSI2201


Course Python Programming
Course / Branch B.E – Common to all branches
Title Implement range() function in python

INTRODUCTION
OBJECTIVE OF THE EXERCISE
To perform the following exercises using Python
1. Display all the Capital Letters using range function
2. Display the multiplication table for N * N
3. Generate the following pattern
*
* *
* * *
* * * *
* * * * *

SYNTAX
Syntax – range()
Range(lower_limit,upper_limit,increment/decrement)
Statement(s)

SOLUTION
1. for a in range(65,91,1)
print(chr(a),end=" ")

2. row=int(input("Enter rows "))


col=int(input("Enter columns "))
for i in range(1, row+1)
for j in range(1, col+1)
print(format(i * j,"4d"),end=" ")
print()

3. n=5

7|Page
for i in range(n)
for j in range(i)
print ('* ', end="")

8|Page
Exercise 04

Course Code U18CSI2201


Course Python Programming
Course / Branch B.E – Common to all branches
Title Implement various control statements in python

INTRODUCTION
OBJECTIVE OF THE EXERCISE
To perform the following exercises using Python
1. Write a program to find all numbers between 2000 and 3000 (both inclusive) which are
divisible by 7 but not a multiple of 5. All such numbers are to be printed in a comma
separated sequence on a single line.
Output 2002, 2009, 2016, … 3199
2. Consider the scenario of retail store management again. The store provides discount
for all bill amounts based on the criteria below
Bill Amount Discount Percentage
>=1000 5
>=500 and <1000 2
>0 and <500 1

Write a Python program to find the net bill amount after discount. Observe the output
with different values of bill amount. Assume that bill amount will be always greater
than zero.

3. Write a program to compute the factorial of a given number.


Test Case 1 2 3 4
Input 8 1 0 -5
Output 40320 1 1 Invalid
4. Write a program to solve this classic ancient Chinese puzzle We count 35 heads and
94 legs among the chickens and rabbits in a farm. How many rabbits and how many
chickens do we have?
5. Generate the prime numbers in the range of 100 to 200.
6. Read any input string from the user which contains more than one word with a space.
Illustrate the removal of space using continue keyword.
Test Case 1 2
Input Welcome to Python Programming Hello World
Output WelcometoPythonProgramming HelloWorld

9|Page
SYNTAX
Syntax – IF Statement
if expression
statement_1
statement_2
Syntax – IF-ELSE Statement
if expression
statement_1
statement_2
....
else
statement_3
statement_4
....
Syntax – IF-ELIF Statement
if expression1
statement_1
statement_2
....

elif expression2
statement_3
statement_4
....
elif expression3
statement_5
statement_6
....................
else
statement_7
statement_8
Syntax –FOR loop
for itr_seq in expression
statement(s)
Syntax – WHILE loop
while expression
statement(s)

SOLUTION
1. for i in range(2000, 3201)
if (i%7==0) and (i%5!=0)
print(i,end=',')

2. custid=int(input("Enter Customer id "))

10 | P a g e
if(custid >100 and custid <=1000)
amount = float (input ("Enter billing amount "))
if(amount >= 1000)
dis = amount * 5/100
bill = amount - dis
print("Cash to be paid ",bill)
elif(amount >= 500 and amount <1000)
dis = amount * 2/100
bill = amount - dis
print("Cash to be paid ",bill)
elif(amount >0 and amount <500)
dis = amount * 1/100
bill = amount - dis
print("Cash to be paid ",bill)
else
print("You have not purchased anything")
else
print("Kindly register with us")

3. n=int(input("Enter a number"))
f=1
if(n<0)
print("Negative Number")
elif(n==0)
print(1)
else
for i in range(1, n+1)
f=f*i
print("Factorial ",f)

4. heads=35
legs=94
for rabbits in range(heads)
chickens = heads - rabbits
11 | P a g e
if 2 * chickens + 4 * rabbits == legs
print("No.of chickens = " , chickens,"No.of Rabbits=", rabbits)

5. for n in range(100,200)
if(n==2)
print(n)
else
for i in range(2,n)
if(n%i == 0)
break
else
print(n, end=',')
print('')
6. a=input("Enter string ")
print("You have entered ",a)
print("After space removal")
for i in a
if i==" "
continue
print(i,end="")

12 | P a g e
Exercise 06

Course Code U18CSI2201


Course Python Programming
Course / Branch B.E /CSE
Title Demonstrate string functions using python

INTRODUCTION
OBJECTIVE OF THE EXERCISE
To perform the following exercises using Python
1. Write a program (using functions) that takes a long sentence with multiple words as
input and rearranges the words in the sentence in the reverse order.

Test 1 2 3
Case
Input My name is Kumaraguru College of Problem based on
python Technology Strings
Output python is name Technology of College Strings on based
My Kumaraguru Problem

2. Write a program that accepts a sentence as input and calculates the number of letters,
digits and special characters.
Test Case 1 2
Input sentence hello world! @$ There is a laptop with #CS123…
123
Output Letters 10 20
Digits 3 3
Special 3 4
Character
s

3. Write a program that takes a long sentence with multiple words as input and replace the
string “python” into python programs .
Test Case 1 2
Input My name is python Problem based on python
Output My name is python programs Problem based on python string

4. Write a Python function that accepts a string and calculate the number of upper case letters
and lower case letters. Sample String The quick Brow Fox;
Expected Output

13 | P a g e
No. of Upper case characters 3
No. of Lower case Characters 12
SYNTAX
a) Procedure for doing the EXERCISE

1. split()

split() method returns a list of strings after breaking the given string by the specified
separator.
Syntax str.split(separator, maxsplit)
2. isdigit() is a built-in method used for string handling. The isdigit() methods returns
“True” if all characters in the string are digits, Otherwise, It returns “False”.
isalpha() is a built-in method used for string handling. The isalpha() methods returns
“True” if all characters in the string are alphabets, Otherwise, It returns “False”.

3. replace()-The replace() method replaces a string with another string


4. islower()-Returns True if all characters in the string are lower case

isupper()-Returns True if all characters in the string are upper case

5. join()- The method provides a flexible way to concatenate string. It concatenates each
element of an iterable (such as list, string and tuple) to the stringand returns the
concatenated string.

SAMPLE PROGRAM

1.a=input("enter the string")


x=a.split()
y=len(x)
while (y>0)
print(x[y-1],end=" ")
y=y-1

2. S='hello@!12'
d=l=char=0
for c in s
if c.isdigit()
d=d+1
elif c.isalpha()
l=l+1
else
char=char+1

14 | P a g e
print("Letters", l)
print("Digits", d)
print(‘special character’, Char)

3. name=” My name is python”


print (song.replace('python', 'python program '))

4. a=”The quick Brow Fox”


N=len(a)
For i in range (0,n)

If(a.islower()==true)
Lower++
Elif(a. isupper()== true)
Upper++
Print(“No. of Upper case characters”, upper, “No. of Lower case Characters” ,lower)

15 | P a g e
Exercise 07

Course Code U18CSI2201


Course Python Programming
Course / Branch B.E /CSE
Title Implement user defined functions using python.

INTRODUCTION
OBJECTIVE OF THE EXERCISE
To perform the following exercises using Python
1. Write a function “calc_weight_ on_ planet()” that takes two arguments - weight on Earth
and the surface gravity of the other planet and calculates the equivalent weight on the other
planet. (Note The surface gravity of Jupiter is 23.1 m/s2 (approx) and that of Earth is 9.8
m/s2(approx), Weight = Mass x Surface gravity)
Test case 1 2
Weight on 127.2 -100
Earth(lb)
Weight on Jupiter 297.6 Invalid

2. A pangram is a sentence that contains all the letters of the English alphabet at least once.
Write a function to check if a given sentence is a pangram or not. If the given sentence is not a
pangram print the missing letters.

Test case 1 2
Input The quick brown fox The quick brown rat jumps over the
jumps over the lazy lazy cat
dog
Output Pangram Not a Pangram
Missing lettersf,x,d,g

3. Write a version of a palindrome recognizer that also accepts phrase palindromes such as "Go
hang a salami I'm a lasagna hog.". (Note punctuation, capitalization and spacing are ignored)
Test case 1 2
Input i am tired was it a rat i saw
Output Not a palindrome Palindrome

4) . Write python for recursive function to calculate Fibonacci series


5) Write a function printValue() that can accept two strings as input and prints the longer of
the two. If two strings have the same length, then the function should print both the strings.
Test 1 2 3
case
Input printValue(“one”,”t printValue(“laptop”,”lapt printValue(“ten”,”
hree”) op”) so”)

16 | P a g e
Output Three laptop ten
laptop

SYNTAX
a) Procedure for doing the EXERCISE

Syntax

def function_name (arguments)


statements
functionname(arguments )

Sample program
1. def jupi(wt,sg)
sg_e=9.8
m=wt/sg_e
wt_j=m*sg
print(wt_j)
wt=float(input("enter wt in earth"))
sg=float(input("surface gravity of jupiter"))
jupi(wt,sg)

2. myPhrase = "The quick brown fox jumps over the lazy dog"

def is_pangram(phrase)
c=0
alphabet = "abcdefghijklmnopqrstuvwxyz"
phraseLetters = ""
for char in phrase
for letter in alphabet
if char == letter and char not in phraseLetters
phraseLetters += char
for char in phraseLetters
for letter in alphabet
if char == letter
c += 1
if c == 26
return True
else
print( phraseLetters, alphabet)
return False

print is_pangram(myPhrase)

3. import string
ignored = string.punctuation + " "

17 | P a g e
def is_palindrome(str1)
cleanstr = ""
for i in str1
cleanstr += "" if i in ignored else i

return cleanstr.lower() == cleanstr[-1].lower()

str1=input("enter the string")

print(is_palindrome(str1))

4. def recur_fibo(n)
print “Fibonacci sequence"
if n <= 1
return n
else
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms =input(“enter the number”)
if nterms <= 0
print("Please enter a positive integer")
else
print("Fibonacci sequence")
for i in range(nterms)
print(recur_fibo(i))

5) def printvalue(a,b)
x=len(a)
y=len(b)
if(x>y)
print(a)
elif(x<y)
print(b)
else
print(a)
print(b)
printvalue("ravi","ram")

Exercise 8

18 | P a g e
Course Code U18CSI2201

Course Python Programming


Course / Branch B.E /CSE
Title Develop python programs to perform operations
on list

INTRODUCTION
OBJECTIVE OF THE EXERCISE
To perform the following exercises using Python

1. Write a program that prompts the user to enter a list of words and stores them in a list. Create
a new list that retrieves words from the first list such that first letter occurs again within the
word. The program should display the resulting list.
Test case 1 2
Input Baboon, List, Duplicate Frog, Snake, Lizard
Output Baboon No Such word exist in list

2. Write a program that prompts the user to enter the name of the fruit and its weight. The
program should then display the information in the same form but in the alphabetical order.
Test 1 2 3
case
Input Kiwi, 4 kg; Gowva, 4 kg; Apple, Carrot, 4 kg; Kiwi, 6
Apple, 6 kg; 6 kg; Banana, 11 kg kg; Banana, 11 kg
Banana, 11 kg
Output Apple, 6 kg; Apple, 6 kg;Banana, Banana, 11 kg;
Banana, 11 kg; 11 kg;Gowva, 4 kg Carrot, 4 kg; Kiwi, 6
Kiwi, 4 kg kg

3. Write a program for binary search using list


Test case 1 2
Input 4, 7,8,11,21 4, 7,8,11,21
Enter the number to be search 11 18
Output The number is The number is not
present present

4. Write a program that accepts a sequence of words that are hyphen separated as input and
prints the words in a hyphen-separated sequence after sorting them alphabetically.
Test 1 2 3
case
Input green-red-yellow-black- red-yellow-black green-yellow-
white white
Output black-green-red-white- black -red-yellow green-white-
yellow yellow

19 | P a g e
5. Write a program to sort the (name, age, score) tuples in ascending order where name is string,
age and score are numbers. The tuples are input using the console. The sort criteria are
a. Sort based on name
b. Then sort based on age;
c. Then sort by score

Test case 1 2
Input Tom,19,80 Jony,17,91
John,20,90 Jony,17,93
Jony,17,91 Json,21,85
Output [('John', '20', '90'), ('Jony', '17', [('Jony', '17', '91'),
'91'), ('Jony', '17', '93'),('Tom', ('Jony', '17', '93'), ('Json',
'19', '80')] '21', '85')]

6. Write a program that accepts a sequence of words that are hyphen separated as input and
concatenate elements of a list without hyphen

Test 1 2 3
case
Input green-red-yellow-black- red-yellow-black green-yellow-
white white
Output greenredyellowblackwhite redyellowblack greenyellowwhite

SYNTAX
a) Procedure for doing the EXERCISE

List()-List is a collection which is ordered and changeable. Allows duplicate members.

List=[set of number,” set of string”]

Accessing the list

To access values in lists, use the square brackets for slicing along with the index or indices to

obtain value available at that index.

List[0]- 0 as index value

append(object) - Updates the list by adding an object to the list.

sort () -can be used to sort a list in ascending, descending or user defined order

join()- method is a string method and returns a string

20 | P a g e
string_name. join(iterable)

SAMPLE PROGRAM

1. list = []
check = 0
n = int(input("Enter the number of words you want to add to list "))
for i in range(n)
x = input("Enter the words ")
list.append(x)
print("original list ", list)
for x in range(len(list))
b = list[x]
for y in range(len(b) - 1)
if b[0] == b[y + 1]
print(b)
check = 1
break
if check == 0
print("No such words exist in the list")

2. a = [x for x in input().split(';')]
a.sort()
print(a)

3. def binarySearch(alist, item)


first = 0

last =(len(alist))-1
found = False
while first<=last and not found
midpoint = int((first + last)/2)
if alist[midpoint] == item
print("Item found in position ", midpoint ,"is", alist[midpoint])
found = True
else
if item < alist[midpoint]
last = midpoint-1
else
first = midpoint+1
return found
testlist1 = [0,12,1,15,4,10,13,3]
testlist = sorted(testlist1)
print(testlist)
print(binarySearch(testlist, 3))

21 | P a g e
print(binarySearch(testlist, 14))

4. items=[n for n in input().split('-')]


items.sort()
print('-'.join(items))

5. from operator import itemgetter

persons = []
while True
line = input("> ")
if not line
break
persons.append(tuple(line.split(',')))

persons = sorted(persons, key=itemgetter(0))

for person in persons


print (','.join(person))

6. color = ['red', 'green', 'orange']


print('-'.join(color))
print(''.join(color))

Exercise 9

Course Code U18CSI2201

22 | P a g e
Course Python Programming
Course / Branch B.E /CSE
Title Implement dictionary and set in python

INTRODUCTION
OBJECTIVE OF THE EXERCISE
To perform the following exercises using Python
1). Consider the following lists, A = [1,1,2,3,5,8,13,21,34,55,89] &
B = [1,2,3,4,5,6,7,8,9,10,11,12,13]
Write a program that returns a list that contains only the elements that are common
between the lists (without duplicates). Make sure your program works on two lists of
different sizes.
Hint (A intersection B)
Test cases
Input the following lists,
A = [1,1,2,3,5,8,13,21,34,55,89] B = [1,2,3,4,5,6,7,8,9,10,11,12,13]
Output A ∩ B= [1,2,3,5,8,13]

2). Write a python program to get the set of values in dictionary and sort according to the key
values.

3). Create a dictionary of the days in the months of the year


In this dictionary, keys are month names and whose values are the number of days in the
corresponding months
days = {'January'31, 'February'28, 'March'31, 'April'30, 'May'31, 'June'30, 'July'31, 'August'31,
'September'30, 'October'31, 'November'30, 'December'31}
(a) Ask the user to enter a month name and use the dictionary to tell them how many
days are in the month.
(b) Print out all of the keys in alphabetical order.
(c) Print out all of the months with 31 days.

(d) Print out the (key-value) pairs sorted by the number of days in each month
4) Write a program to compute the frequency of the words from the input. The output should
output after sorting the key alphanumerically.

5) Write a python program takes a string and creates a dictionary with key as first character
and value as words starting with that character.
• Enter a string and store it in a variable.
• Declare an empty dictionary.
• Split the string into words and store it in a list.
• Using a for loop and if statement check if the word already present as a key in the
dictionary.
• If it is not present, initialize the letter of the word as the key and the word as the value
and append it to a sublist created in the list. If it is present, add the word as the value
to the corresponding sublist. Print the final dictionary.

23 | P a g e
SYNTAX
a) Procedure for doing the EXERCISE

A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries


are written with curly brackets, and they have keys and values.
Dictionary = {"key" "value" }
Create set in python
setx = set()

n = set([0, 1, 2, 3, 4, 5])

SAMPLE PROGRAM
1. a = [0,1,2,0]
b = [1,1,5,7]
c=list(set(a))
d=list(set(a)&set(b))#intersection
e=list(set(a)|set(b))#union
f=list(set(a)-set(b))#new set with elements in s but not in t
g=set(a)<=set(b) #test whether every element in s is in t
print(c,d)
print(e,f)
print(g)

2. Dict = {'Tim' 18,'Charlie'12,'Tiffany'22,'Robert'25}


Boys = {'Tim' 18,'Charlie'12,'Robert'25}
Girls = {'Tiffany'22}
Students = list(Dict.keys())
Students.sort()
for S in Students
print("".join((S,str(Dict[S]))))

3. import operator
days = {'January'31, 'February'28, 'March'31, 'April'30, 'May'31, 'June'30, 'July'31,
'August'31, 'September'30, 'October'31, 'November'30, 'December'31}
print(sorted(days))
#to print the months who days is 31
for k,v in days.items()
if (v==31)
print(k)
print("Dict comprehension")
#d1=[(k,v) for v,k in days]
#print(d1)
#sorting based on days
print("Sorting based on days")
d1 = sorted(days.items(), key=operator.itemgetter(1))
print(d1)
#method 3-

24 | P a g e
print("sort by days")
for x in sorted(days.items(),key=operator.itemgetter(1))
print(x)

4)
Fr eq = {} # frequency of words in text
line = input()
for word in line.split()
freq[word] = freq.get(word,0)+1
words = freq.keys()
words.sort()
for w in words
print "%s%d" % (w,freq[w])

5) test_string=raw_input("Enter string")
l=test_string.split()
d={}
for word in l
if(word[0] not in d.keys())
d[word[0]]=[]
d[word[0]].append(word)
else
if(word not in d[word[0]])
d[word[0]].append(word)
for k,v in d.items()
print(k,"",v)

Exercise 10

Course Code U18CSI2201


Course Python Programming

25 | P a g e
Course / Branch B.E /CSE
Title Develop programs to work with Tuples.

INTRODUCTION
OBJECTIVE OF THE EXERCISE

1. Write a program to sort the (name, age, score) tuples in ascending order where name is string,
age and score are numbers. The tuples are input using the console. The sort criteria are
a) Sort based on name
b) Then sort based on age;
c) Then sort by score

Test case 1 2
Input Tom,19,80 Jony,17,91
John,20,90 Jony,17,93
Jony,17,91 Json,21,85
Output [('John', '20', '90'), ('Jony', '17', [('Jony', '17', '91'),
'91'), ('Jony', '17', '93'),('Tom', ('Jony', '17', '93'), ('Json',
'19', '80')] '21', '85')]

2) Define a function which can generate and print a tuple where the value are square of
numbers between 1 and 20 (both included).

Hints Use ** operator to get power of a number


Use range() for loops.
Use list.append() to add values into a list.
Use tuple() to get a tuple from a list

SYNTAX
A) Procedure for doing the EXERCISE

A tuple is a collection which is ordered and unchangeable. In Python tuples are written with
round brackets.

Tuples_name(1,2,3)

Sample Program
1. from operator import itemgetter

persons = []
while True
line = input("> ")
if not line
break
persons.append(tuple(line.split(',')))

persons = sorted(persons, key=itemgetter(0))

26 | P a g e
for person in persons
print (','.join(person))

2) def printTuple()
li=list()
for i in range(1,21)
li.append(i**2)
printTuple()
print tuple(li)

Exercise 11

Course Code U18CSI2201


Course Python Programming
Course / Branch B.E /CSE

27 | P a g e
Title Create programs to solve problems using
various data structures in python

INTRODUCTION
OBJECTIVE OF THE EXERCISE

1) Write a program that maps a list of words to a list of integers (representing the lengths of the
corresponding words). Write it in three different ways 1) using a for-loop, 2) using the higher
order function map (), and 3) using list comprehensions
2) Write a program that prompts the user to enter the name of the fruit and its weight. The
program should then display the information in the same form but in the alphabetical order.
Test 1 2 3
case
Input Kiwi, 4 kg; Gowva, 4 kg; Apple, Carrot, 4 kg; Kiwi, 6
Apple, 6 kg; 6 kg; Banana, 11 kg kg; Banana, 11 kg
Banana, 11 kg
Output Apple, 6 kg; Apple, 6 kg;Banana, Banana, 11 kg;
Banana, 11 kg; 11 kg;Gowva, 4 kg Carrot, 4 kg; Kiwi, 6
Kiwi, 4 kg kg
3. Write a program that prompts the user to enter a list of words and stores them in a list. Create
a new list that retrieves words from the first list such that first letter occurs again within the
word. The program should display the resulting list.
Test case 1 2
Input Baboon, List, Duplicate Frog, Snake, Lizard
Output Baboon No Such word exist in list

4. Please write a program to generate all sentences where subject is in ["I", "you"] and verb is
in ["Play", "Love"] and the object is in ["Hockey","Football"].
Hints Use list[index] notation to get a element from a list

5) Write a program to compute the frequency of the words from the input. The output should
output after sorting the key alphanumerically

SAMPLE PROGRAM

1)using a for-loop
def map(words)
lengths = []
for word in words
lengths.append(len(word))
return lengths
words = ['abv', 'try me', 'test']
print (map(words))

2) a = [x for x in input().split(';')]
28 | P a g e
a.sort()
print(a)

3) list = []
check = 0
n = int(input("Enter the number of words you want to add to list "))
for i in range(n)
x = input("Enter the words ")
list.append(x)
print("original list ", list)
for x in range(len(list))
b = list[x]
for y in range(len(b) - 1)
if b[0] == b[y + 1]
print(b)
check = 1
break
if check == 0
print("No such words exist in the list")

4) subjects=["I", "You"]
verbs=["Play", "Love"]
objects=["Hockey","Football"]
for i in range(len(subjects))
for j in range(len(verbs))
for k in range(len(objects))
sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k])
print sentence

5)
freq = {} # frequency of words in text
line = input()
for word in line.split()
freq[word] = freq.get(word,0)+1
words = freq.keys()
words.sort()
for w in words
print "%s%d" % (w,freq[w])

Exercise 12

29 | P a g e
Course Code U18CSI2201
Course Python Programming
Course / Branch B.E /CSE
Title Implement python program to perform file
operations.

INTRODUCTION
OBJECTIVE OF THE EXERCISE
1. Write a Python program to read a file line by line and store it into a list.
Sample Solution-
Python Code

def file_read(fname)

with open(fname) as f

#Content_list is the list that contains the read lines.

content_list = f.readlines()

print(content_list)

file_read(\'test.txt\')
2. Given lower and upper limits, generate a given count of random numbers within
a given range, starting from ‘start’ to ‘end’ and store them in list.
Examples

Input num = 10, start = 20, end = 40


Output [23, 20, 30, 33, 30, 36, 37, 27, 28, 38]
The output contains 10 random numbers in
range [20, 40].

Input num = 5, start = 10, end = 15


Output [15, 11, 15, 12, 11]
The output contains 5 random numbers in
range [10, 15].
import random

# Function to generate
# and append them
# start = starting range,
# end = ending range
# num = number of
# elements needs to be appended
def Rand(start, end, num)

30 | P a g e
res = []

for j in range(num)
res.append(random.randint(start, end))

return res

# Driver Code
num = 10
start = 20
end = 40
print(Rand(start, end, num))
Output
[23, 20, 30, 33, 30, 36, 37, 27, 28, 38]
3. Write a Python program to read last n lines of a file.
import sys
import os
def file_read_from_tail(fname,lines)
bufsize = 8192
fsize = os.stat(fname).st_size
iter = 0
with open(fname) as f
if bufsize > fsize
bufsize = fsize-1
data = []
while True
iter +=1
f.seek(fsize-bufsize*iter)
data.extend(f.readlines())
if len(data) >= lines or f.tell() == 0
print(''.join(data[-lines]))
break
file_read_from_tail('test.txt',2)

3. Python Program to count the occurrences of a word in a text file. The program
output is also shown below.
fname = input("Enter file name ")
word=input("Enter word to be searched")
k=0
with open(fname, 'r') as f
for line in f
words = line.split()
for i in words
if(i==word)
k=k+1
print("Occurrences of the word")
print(k)
Case 1
Contents of file

31 | P a g e
hello world hello
hello

Output
Enter file name test.txt
Enter word to be searchedhello
Occurrences of the word
3

Case 2
Contents of file
hello world
test
test test
Output
Enter file name test1.txt
Enter word to be searchedtest
Occurrences of the word
4

4. Write a python program to process the employee data in employee.txt and calculate
the income of the employee
inputFile = open ("employees.txt", "r")
print ("Reading from file input.txt")
for line in inputFile
name,job,income = line.split(',')
last,first = name.split()
income = int(income)
income = income + (income * BONUS)
print("Name %s, %s\t\t\tJob %s\t\tIncome $%.2f" %(first,last,job,income))
print ("Completed reading of file input.txt")
inputFile.close()

5. Write a python program to copy the contents of the file info.txt to the (new) file info
lined.txt

file_in = open("info.txt", "r")


file_out = open("info_lined.txt", "w")
count = 0
for line in file_in
count = count + 1
file_out.write("{2d} {}".format(count, line))
file_out.close()

32 | P a g e
Exercise 13

Course Code ` U18CSI2201


Course Python Programming
Course / Branch B.E /CSE
Title Implement python programs using modules and
packages.

INTRODUCTION
OBJECTIVE OF THE EXERCISE
1. Demonstration of the importing math module to gain access to the methods and attributes
of the math module.
import math
type(math)
<class ’module’>
dir(math)
help(math.cos) # Obtain help on math.cos.
# Help on built-in function cos in module math

cos(...)
cos(x)
Return the cosine of x (measured in radians).
math.cos(0) # Cosine of 0.
math.pi # math module provides pi = 3.1414...
math.cos(math.pi) # Cosine of pi.
cos(0)

2. Demonstration of the cmath module which provides support for complex numbers.
>>> dir(cmath)
[’__doc__’, ’__file__’, ’__name__’, ’__package__’, ’acos’, ’acosh’, ’asin’, ’asinh’,
’atan’, ’atanh’, ’cos’, ’cosh’, ’e’, ’exp’,
’isfinite’, ’isinf’, ’isnan’, ’log’, ’log10’, ’phase’, ’pi’,
’polar’, ’rect’, ’sin’, ’sinh’, ’sqrt’, ’tan’, ’tanh’]
>>> z1 = 1j
>>> cmath.sqrt(z1)
(0.7071067811865476+0.7071067811865475j)
>>> cmath.cos(5.6 - 7.6j)
(774.8664714775274-630.6970442971782j)
>>> z2 = 3 + 4j
>>> cmath.polar(z2)
(5.0, 0.9272952180016122)

3. Write a python code to import your own module


"""
This module contains two functions and one globally defined
integer.
"""
scale = 2

33 | P a g e
def scaler(arg)
"""Return the scaled value of the argument."""
return scale * arg

def reverser(xlist)
"""Return the reverse of the argument."""
# Reverse using a slice with negative increment and default start
# and stop.
return xlist[ -1]

Importation and use of the module

import my_mod
>>> my_mod.scale
2
>>> my_mod.scaler(42.0)
84.0
>>> my_mod.scaler("liar")
’liarliar’
>>> my_mod.reverser("!pleH")
’Help!’
>>> my_mod.scale = 3 # Change value of my_mod.scale.
>>> my_mod.scaler("La") # See that change affects my_mod.scaler().
’LaLaLa’
>>> help(my_mod)

3. Demonstrate with a very simple example how to create a package with some Python
modules.
First of all, we need a directory. The name of this directory will be the name of the package,
which we want to create. We will call our package "simple_package". This directory needs to
contain a file with the name "__init__.py". This file can be empty, or it can contain valid Python
code. This code will be executed when a package will be imported, so it can be used to initialize
a package, e.g. to make sure that some other modules are imported or some values set. Now
we can put into this directory all the Python files which will be the submodules of our module.
We create two simple files a.py and b.py just for the sake of filling the package with modules.
The content of a.py
def bar()
print("Hello, function 'bar' from module 'a' calling")

The content of b.py


def foo()
print("Hello, function 'foo' from module 'b' calling")
We will also add an empty file with the name __init__.py inside of simple_package directory.

34 | P a g e
>>> import simple_package
Importing modules
>>> from simple_package import a, b
>>> a.bar()
Hello, function 'bar' from module 'a' calling
>>> b.foo()
Hello, function 'foo' from module 'b' calling

Or
import simple_package.a
import simple_package.b
It will work now
>>> import simple_package
>>>
>>> simple_package.a.bar()
Hello, function 'bar' from module 'a' calling
>>>
>>> simple_package.b.foo()
Hello, function 'foo' from module 'b' calling

35 | P a g e

You might also like