Lab Manual U18csi2201 Python Programming
Lab Manual U18csi2201 Python Programming
Laboratory Manual
1|Page
Exercise 01
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
4|Page
Exercise 02
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))
6|Page
Exercise 03
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=" ")
3. n=5
7|Page
for i in range(n)
for j in range(i)
print ('* ', end="")
8|Page
Exercise 04
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.
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=',')
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
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”.
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
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)
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
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
16 | P a g e
Output Three laptop ten
laptop
SYNTAX
a) Procedure for doing the EXERCISE
Syntax
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
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
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
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
To access values in lists, use the square brackets for slicing along with the index or indices to
sort () -can be used to sort a list in ascending, descending or user defined order
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)
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))
persons = []
while True
line = input("> ")
if not line
break
persons.append(tuple(line.split(',')))
Exercise 9
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.
(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
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)
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
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).
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(',')))
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
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 = 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
# 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
32 | P a g e
Exercise 13
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)
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]
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")
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