Python Programming Lab Manual (1)
Python Programming Lab Manual (1)
Program 1
1. Write a Python Script to demonstrate
Variable
Executing Python from the Command Line
Editing Python Files
Reserved Words
b) Write a python program to add two numbers.
c) Write a program to demonstrate different number data types in python.
d) Write a program to perform different arithmetic operations on numbers in
python.
y = "John"
z = 10.5
print(x)
print(y)
print(z)
Output
John
10.5
Step 3 Enter
Output
Hello World!
f.close()
Output
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
as elif in try
Output
Type a number: 12
#String
x = "Hello World"
#display x:
print(x)
print(type(x))
#Numeric Types
#Int
x = 20
#display x:
print(x)
print(type(x))
#Float
x = 20.5
#display x:
Python Programming Lab Manual (U21CM3L1)
print(x)
print(type(x))
#complex
x = 1j
#display x:
print(x)
print(type(x))
Output
Hello World
<class 'str'>
20
<class 'int'>
20.5
<class 'float'>
1j
<class 'complex'>
print(x + y)
print(x - y)
print(x * y)
print(x / y)
Output
Enter a number x: 10
Enter a number y: 5
15
50
2.0
Python Programming Lab Manual (U21CM3L1)
Program 2
a) Write a python program to print a number is positive/negative using if-else.
b) Write a python program to find largest number among three numbers.
c) Write a Python program to swap two variables
d) Python Program to print all Prime Numbers in an Interval
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output
Enter a number: 4
Positive number
Enter a number: 0
Zero
Enter a number: -6
Negative number
Python Programming Lab Manual (U21CM3L1)
b) Source Code: Write a python program to find largest of three numbers using the logical
operator
num1 = int(input("Enter first number: "))
largest = num1
largest = num2
else:
largest = num3
Output
temp = x
x=y
y = temp
Output
Enter value of x: 5
Enter value of y: 10
lower = 2
upper = 15
Program 3
a) Write a python program to check whether the given string is palindrome or not.
b) Write a program to create, concatenate and print a string and accessing
substring from a given string.
c) Functions: Passing parameters to a Function, Variable Number of Arguments,
Scope, and Passing Functions to a Function
a) Source Code - python program to check whether the given string is palindrome or not.
def isPalindrome(s):
What is a Palindrome?
return s == s[::-1]
A palindrome is nothing but any number or a string
which remains unaltered when reversed.
# Driver code
s = "malayalam" Example: 12321
ans = isPalindrome(s) Output: Yes, a Palindrome number
Output
Yes
Python Programming Lab Manual (U21CM3L1)
b) Source code - Write a program to create, concatenate and print a string and accessing
substring from a given string.
# Defining strings
str1 = "Welcome to"
str2 = "Python Programming Lab "
str4 = "abc"
# printing original string
print("The original string is : " + str4)
# printing result
print("All substrings of string are : " + str(res))
Output
A function is a block of code which only runs when it is called. We can pass data, known as
parameters, into a function. A function can return data as a result.
Syntax of Function
deffunction_name(parameters):
"""docstring"""
statement(s)
Explanation – a. Passing parameters to a Function
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are
passed into a function.
Source Code: Write a python program to demonstrate how to pass parameters to a function
Arguments
print("Argument Example")
defmy_function(fname):
print(fname + " khan")
my_function("Saba")
my_function("Salman")
my_function("Zohran")
Output
Argument Example
Saba khan
Salman khan
Zohran khan
Explanation – c. Scope
Python Scope
A variable is only available from inside the region it is created. This is called scope.
# Global scope
s = "I love Python"
f()
print(s)
defmy_func():
# local scope
x = 10
print("Value inside function:",x)
# Global scope
Python Programming Lab Manual (U21CM3L1)
x = 20
my_func()
print("Value outside function:",x)
OUTPUT
Me too.
I love Python
Value inside function: 10
Value outside function: 20
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function
calls itself. This has the benefit of meaning that you can loop through data to reach a result.
The following image shows the working of a recursive function called recurse.
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output
The factorial of 3 is 6
Python Programming Lab Manual (U21CM3L1)
Program 4
a) Create a list and perform the following methods
1) insert () 2) remove() 3) append() 4) len() 5) pop() 6)clear()
b) Create a dictionary and apply the following methods
1) Print the dictionary items 2) access items 3) useget () 4) change values 5) use
len()
c) Create a tuple and perform the following methods
1) Add items 2) len() 3) check for item in tuple 4)Access items
a) Source Code - Write a program to create, append, and remove lists in python.
print("Create a list")
thislist = ["apple", "banana", "cherry"]
print(thislist)
print("Remove an item")
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
print("Empty list")
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Output
Create a list
['apple', 'banana', 'cherry']
Add an item at a specified index
['apple', 'orange', 'banana', 'cherry']
Get the length of a list
3
Add an item to the end of the a list
['apple', 'banana', 'cherry', 'orange']
Remove an item
['apple', 'cherry']
Remove the last item
['apple', 'banana']
Remove an item at a specified index
['banana', 'cherry']
Empty list
Python Programming Lab Manual (U21CM3L1)
b) Source Code - Creating Python Dictionary, accesing items , use get() method , change
values & Len()
print("1.Create and print a dictionary:")
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
x = thisdict.get("model")
print("empty dictionary")
mydict = {}
Output
1.Create and print a dictionary:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
2. Accessing Items:
3. Using get() Method:
Get the value of the model key:
4. Change values:
5.Print the number of items in the dictionary:
3
empty dictionary
Python Programming Lab Manual (U21CM3L1)
c) Source Code - Write a program to Create a tuple and perform the following
methods Add items, check for item in tuple, Access items & use len()
print(“2.Add Items”)
#Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
print(thistuple)
print("3.Check if a tuple item exists")
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Output
1. Create a tuple
('apple', 'banana', 'cherry')
2.Add Items
('apple', 'banana', 'cherry', 'orange')
3.Check if a tuple item exists
Yes, 'apple' is in the fruits tuple
4.Access tuple items
banana
Loop through a tuple
Python Programming Lab Manual (U21CM3L1)
apple
banana
cherry
5.Get the length
3
Python Programming Lab Manual (U21CM3L1)
Program 5
Explanation – Classes
Python Classes/Objects
Python is an object oriented programming language. Almost everything in Python is an
object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
#Note: The __init__() function is called automatically every time the class is being used to
create a new object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Saad", 36)
print(p1.name)
print(p1.age)
OUTPUT
Saad
36
Python Programming Lab Manual (U21CM3L1)
Explanation – File Organization
File Handling
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition, you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
next(file) Returns the next line from the file each time it is called.
file.readlines() Reads until EOF and returns a list containing the lines.
# Close file
f = open("itworkshop.txt", "r")
print(f.readline())
f.close()
#Check if file exists, then delete it:
import os
if os.path.exists("abcd.txt"):
os.remove("abc.txt")
else:
print("The file does not exist")
#Delete file
import os
os.remove("abc.txt")
OUTPUT
OUTPUT
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__']
def __init__(self):
print("Init is called")
A()
OUTPUT
Creating instance
Init is called
def perimeter(self):
p=self.side1 + self.side2 + self.side3 + self.side4
print("perimeter=",p)
q1=quadriLateral(7,5,6,4)
q1.perimeter()
class rectangle(quadriLateral):
def __init__(self, a, b):
super().__init__(a, b, a, b)
r1=rectangle(10, 20)
r1.perimeter()
OUTPUT:
Python Programming Lab Manual (U21CM3L1)
perimeter= 22
perimeter= 60
Polymorphism means the ability to take various forms. In Python, Polymorphism allows us to
define methods in the child class with the same name as defined in their parent class.
As we know, a child class inherits all the methods from the parent class. However, you will
encounter situations where the method inherited from the parent class doesn't quite fit into the
child class. In such cases, we will have to re-implement method in the child class. This
process is known as Method Overriding.
class B(A):
def explore(self):
print("explore() method from class B")
b_obj =B()
a_obj =A()
b_obj.explore()
a_obj.explore()
OUTPUT
explore() method from class B
explore() method from class A
Regular expressions (RegEx), and use Python's re module to work with RegEx (with the help
of examples).
A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. For
example,
^a...s$
The above code defines a RegEx pattern. The pattern is: any five letter string starting
with a and ending with s.
A pattern defined using RegEx can be used to match against a string.
Expression String Matched?
^a...s$ abs No match
alias Match
Python Programming Lab Manual (U21CM3L1)
abyss Match
Alias No match
An abacus No match
Source Code - Python has a module named re to work with RegEx. Here's an example:
import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
OUTPUT
Search successful.
Here, we used re.match() function to search pattern within the test_string. The method
returns a match object if the search is successful. If not, it returns None.
Python RegEx
Python has a module named re to work with regular expressions. To use it, we need to import
the module.
import re
The module defines several functions and constants to work with RegEx.
Character class
A "character class", or a "character set", is a set of characters put in square brackets. The
regex engine matches only one out of several characters in the character class or character set.
We place the characters we want to match between square brackets. If we want to match any
vowel, we use the character set [aeiou].
Source Code - Program to match vowels using RegEx. (re.findall())
import re
s = 'mother of all battles'
result = re.findall(r'[aeiou]', s)
print result
Output
['o', 'e', 'o', 'a', 'a', 'e']
\
Quantifiers in Python
A quantifier has the form {m,n} where m and n are the minimum and maximum times the
expression to which the quantifier applies must match. We can use quantifiers to specify the
number of occurrences to match.
Python Programming Lab Manual (U21CM3L1)
Output
Dot metacharacter
The dot (.) metacharacter stands for any single character in the text.
import re
pattern = re.compile(r'.even')
Output
The seven matches
The revenge matches
re.findall()
The re.findall() method returns a list of strings containing all matches.
Source Code - # Program to extract numbers from a string using RegEx. (re.findall())
#Example 1: re.findall()
Python Programming Lab Manual (U21CM3L1)
import re
OUTPUT
re.split()
The re.split method splits the string where there is a match and returns a list of strings where
the splits have occurred.
import re
If the pattern is not found, re.split() returns a list containing the original string.
Source Code - # Program to Program to remove all whitespaces using RegEx. (re.sub())
#Example 3: re.sub()
# multiline string
string = 'abc 12\
Python Programming Lab Manual (U21CM3L1)
de 23 \n f45 6'
# empty string
replace = ''
# Output: abc12de23f456
OUTPUT
abc12de23f456
If the pattern is not found, re.sub() returns the original string.
re.search()
The re.search() method takes two arguments: a pattern and a string. The method looks for the
first location where the RegEx pattern produces a match with the string.
If the search is successful, re.search() returns a match object; if not, it returns None.
match = re.search(pattern, str)
#Example 5: re.search()
import re
string = "Python is fun"
# check if 'Python' is at the beginning
match = re.search('\APython', string)
if match:
print("pattern found inside the string")
else:
print("pattern not found")
OUTPUT
b) Write a python Program to call data member and function using classes and objects
#Insert a function that prints a greeting, and execute it on the p1 object:
#The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
Python Programming Lab Manual (U21CM3L1)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("Alam", 36)
p1.myfunc()
print(p1.age)
OUTPUT
Program6
a) Write a program to double a given number and add two numbers using lambda()
b) Write a program for filter () to filter only even numbers from a given list.
c) Write a Python Program to Make a Simple Calculator
Syntax
lambda arguments :expression
The expression is executed and the result is returned:
Example
Add 10 to argument a, and return the result:
x = lambda a: a + 10
print(x(5))
Output
15
#Use lambda functions when an anonymous function is required for a short period of
time.
double = lambda x: x * 2
print(double(5))
x = lambda a, b : a + b
print(x(5, 6))
OUTPUT
10
11
Python Programming Lab Manual (U21CM3L1)
b) Source Code – Write a program to filter out only the even items from a list using
Lamda function
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
Output
[4, 6, 8, 12]
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
else:
print("Invalid Input")
Output
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 1
Enter first number: 6
Enter second number: 9
6.0 + 9.0 = 15.0
Python Programming Lab Manual (U21CM3L1)
Program 7
a) Demonstrate a python code to print try, except and finally block statements
b) Write a python program to open and write “hello world” into a file and check
the access permissions to that file?
c) Python program to sort the elements of an array in ascending order and
Descending order
When an error occurs, or exception as we call it, Python will normally stop and generate an
Example
The try block will generate an exception, because x is not defined:
Syntax
try:
print(x)
except:
print("An exception occurred")
Since the try block raises an error, the except block will be executed.
Output
An exception occurred
a) Source Code - Demonstrate a python code to print try, except and finally block
statements
#The finally block gets executed no matter if the try block raises any errors or not:
try:
thislist = ["apple", "banana", "cherry"]
thislist.remove("orange")
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
print(thislist)
Output
Something went wrong
The 'try except' is finished
['apple', 'banana', 'cherry']
Python Programming Lab Manual (U21CM3L1)
b) Source Code - Write a python program to open and write “hello world” into a file and
check the access permissions to that file?
# Close file
f = open("PPLab.txt ", "r")
print(f.readline())
f.close()
#x: it creates a new file with the specified name. It causes an error a file exists with the same
name.
f1 = open("PPLab.txt","x")
print(f1)
if f1:
print("File created successfully")
Output
temp = 0;
print(arr[i],end = "")
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
print()
print(arr[i])
print("________________******************_________________")
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
print()
print(arr[i])
Output
52871
8________________******************_________________
1
Python Programming Lab Manual (U21CM3L1)
Program 8
a) Write a python program to open a file and check what are the access permissions
acquired by that file using os module.
b) Write a program to perform basic operations on random module.
The mkdir() method is used to create the directories in the current working directory. The
syntax to create the new directory is given below.
Syntax
mkdir(directory name)
Syntax
os.getcwd()
The chdir() method is used to change the current working directory to a specified directory.
Syntax
chdir("new-directory")
Deleting directory
Syntax
os.rmdir("directory_name")
Syntax
rename(current-name, new-name)
Python Programming Lab Manual (U21CM3L1)
Remove the specified file
The os module provides the remove () method which is used to remove the specified file.
Syntax
remove(file-name)
import os
os.chdir('C:/Users/admin/Documents')
print(os.getcwd())
import os
#creating a new directory with the name new
os.mkdir(“New Folder”)
os.rename("abc.txt","demofile.txt")
print("The above code renamed current abc.txt to demofile.txt")
import os
os.remove("demofile.txt")
print(“the file has been removed”)
os.rmdir(“New Folder”)
print(“the folder has been deleted”)
Output
C:\Users\admin\Documents
The above code renamed current abc.txt to demofile.txt
the file has been removed”)
Python Programming Lab Manual (U21CM3L1)
The random.randrange() function selects an item randomly from the given range defined by
the start, the stop, and the step parameters. By default, the start is set to 0. Likewise, the step
is set to 1 by default.
Source Code
import random
num = random.randrange(1, 10)
print( num )
num = random.randrange(1, 10, 2)
print( num )
num = random.randrange(0, 101, 10)
print( num )
Output:
4
9
20
Source Code
import random
random_s = random.choice('Random Module') #a string
print( random_s )
random_l = random.choice([23, 54, 765, 23, 45, 45]) #a list
print( random_l )
random_s = random.choice((12, 64, 23, 54, 34)) #a set
print( random_s )
Output:
M
765
54
Python Programming Lab Manual (U21CM3L1)
Explanation –Shuffle Elements Randomly
A general sequence, like integers or floating-point series, can be a group of things like a List /
Set. The random module contains methods that we can use to add randomization to the series.
Code
Output
Program 9
a) Write a python program to practice some basic library modules
NumPy
SciPy
Addition
The add() function sums the content of two arrays, and return the results in a new array.
Subtraction
The subtract() function subtracts the values from one array with the values from another array, and
return the results in a new array.
Multiplication
The multiply() function multiplies the values from one array with the values from another array, and
return the results in a new array.
Division
The divide() function divides the values from one array with the values from another array, and
return the results in a new array.
Power
The power() function rises the values from the first array to the power of the values of the second
array, and return the results in a new array.
Source Code – Write python program to demonstrate the basic functionality of NumPy
Module
print("\n*********Addition*********")
import numpy as np
print(newarr)
print("\n*********Subtraction*********")
Python Programming Lab Manual (U21CM3L1)
import numpy as np
print(newarr)
print("\n*********Multiplication*********")
import numpy as np
print(newarr)
print("\n*********Division*********")
import numpy as np
print(newarr)
print("\n*********Power*********")
import numpy as np
print(newarr)
Output
*********Addition*********
[30 32 34 36 38 40]
*********Subtraction*********
[-10 -1 8 17 26 35]
*********Multiplication*********
*********Division*********
*********Power*********
Constants in SciPy
These constants can be helpful when you are working with Data Science.
Constant Units
A list of all units under the constants module can be seen using the dir() function.
Source Code – Write python program to demonstrate the basic functionality of SciPy
Module
print("*****Constants in SciPy********")
print(constants.pi)
print("*****Constant Units*********")
print(dir(constants))
#Time:
print(constants.minute) #60.0
print(constants.hour) #3600.0
print(constants.day) #86400.0
print(constants.week) #604800.0
print(constants.year) #31536000.0
Python Programming Lab Manual (U21CM3L1)
print(constants.Julian_year) #31557600.0
Output
*****Constants in SciPy********
3.141592653589793
*****Constant Units*********
60.0
3600.0
86400.0
604800.0
31536000.0
31557600.0
Python Programming Lab Manual (U21CM3L1)
Program10
Introduction to basic concept of GUI Programming and Develop desktop based
application with python basic Tkinter() Module.
Source Code – Write python program to demonstrate the basic functionality of SciPy
# Import Module
from tkinter import *
# Execute Tkinter
root.mainloop()
Python Programming Lab Manual (U21CM3L1)
Output
Python Programming Lab Manual (U21CM3L1)
Program 11
Write a python program to create a package (college),subpackage
(alldept),modules(it,cse) and create admin function to module.
import it_module1 as it
import cse_module2 as cse
print(cse.cse_student1)
#College Package
import alldept_subpackage as alldept
print("From Collage")
print(alldept.it.it_student1)
print(alldept.cse.cse_student1)
cse_student1={
"name":"Md Saad",
"rollno":501,
"department":"CSE",
"percent":94.2
}
cse_student2={
"name":"Rahul",
"rollno":502,
"department":"CSE",
"percent":83
}
it_student1={
"name":"Md Saad",
"rollno":501,
"department":"IT",
"percent":90.9
}
it_student2={
"name":"Rahul",
Python Programming Lab Manual (U21CM3L1)
"rollno":502,
"department":"IT",
"percent":85.5
}
#Admin Code
import sys
sys.path.insert(0, '../python/collage') #setting packages path
print("From collage")
print(collage.alldept.it.it_student1)
print(collage.alldept.cse.cse_student1)
Output
From all depertment
{'name': 'Md Saad', 'rollno': 501, 'department': 'IT', 'percent': 90.9}
{'name': 'Md Saad', 'rollno': 501, 'department': 'CSE', 'percent': 94.2}
From Collage
{'name': 'Md Saad', 'rollno': 501, 'department': 'IT', 'percent': 90.9}
{'name': 'Md Saad', 'rollno': 501, 'department': 'CSE', 'percent': 94.2}
From collage
{'name': 'Md Saad', 'rollno': 501, 'department': 'IT', 'percent': 90.9}
{'name': 'Md Saad', 'rollno': 501, 'department': 'CSE', 'percent': 94.2}
Python Programming Lab Manual (U21CM3L1)
Program 12
Write a python program to create a package (Engg), sub
package( years),modules (sem) andcreate staff and student function to
module.
sem1_techers = {
"techer1" : {
"name" : "Moksud Alam Mallik",
"year" : 2011
},
"techer2" : {
"name" : "Kalimulla Alam",
"year" : 2017
},
"techer3" : {
"name" : "Md nur ",
"year" : 2015
}
}
sem1_student = {
"student1" : {
"name" : "Nijamuddin Ahammed",
"year" : 2022
},
"student2" : {
"name" : "Abdul Rahman",
"year" : 2022
},
"student3" : {
"name" : "Minhaj",
"year" : 2022
}
}
print("All Sem")
print(sem.sem1_techers)
print(sem.sem1_student)
Python Programming Lab Manual (U21CM3L1)
#Engineering code goes here
import sys
sys.path.insert(0, './engineering') #setting packages path
#import engineering.years as engg
import years
print("From Enginggring")
print(years.sem.sem1_techers)
print(years.sem.sem1_student)
Output
All Sem
{'techer1': {'name': 'Moksud Alam Mallik', 'year': 2011}, 'techer2': {'name': 'Kalimulla Alam',
'year': 2017}, 'techer3': {'name': 'Md nur ', 'year': 2015}}
{'student1': {'name': 'Nijamuddin Ahammed', 'year': 2022}, 'student2': {'name': 'Abdul
Rahman', 'year': 2022}, 'student3': {'name': 'Minhaj', 'year': 2022}}
From Enginggring
{'techer1': {'name': 'Moksud Alam Mallik', 'year': 2011}, 'techer2': {'name': 'Kalimulla Alam',
'year': 2017}, 'techer3': {'name': 'Md nur ', 'year': 2015}}
{'student1': {'name': 'Nijamuddin Ahammed', 'year': 2022}, 'student2': {'name': 'Abdul
Rahman', 'year': 2022}, 'student3': {'name': 'Minhaj', 'year': 2022}}