Python Programming Lab Manual a.Y 23-24
Python Programming Lab Manual a.Y 23-24
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.
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
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
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
Program 5
Prepared by 1
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
Program 6
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
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
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.
Program 9
a) Write a python program to practice some basic library modules
NumPy
SciPy
Program10
Introduction to basic concept of GUI Programming and Develop desktop based
application with python basic Tkinter() Module.
Program 11
Write a python program to create a package (college),sub package (all
dept),modules(it, cse) and create admin function to module.
Program 12
Write a python program to create a package (Engg), sub package(
years),modules (sem) and create staff and student function to module.
Prepared by 2
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
Program 1
2. 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!
Prepared by 3
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
Source Code – Editing Python Files
f= open("guru99.txt","w+")
for i in range(10):
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
Prepared by 4
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
b) Write a python program to add two numbers.
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
Prepared by 5
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
x = 20.5
#display x:
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'>
Prepared by 6
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
e) Write a program to perform different arithmetic operations on numbers in
python.
Python provides numerous built-in functions that are readily available to us at the Python
prompt.
Some of the functions like input() and print() are widely used for standard input and output
operations respectively
Source Code – To perform Arithmetic Operations
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
Prepared by 7
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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
Prepared by 8
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
largest = num1
largest = num2
else:
largest = num3
Output
Prepared by 9
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
d) Source Code - Python program to swap two variables
temp = x
x=y
y = temp
Output
Enter value of x: 5
Enter value of y: 10
Prepared by 10
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
e) Source Code: Python program to display all the prime numbers in an
interval
lower = 2
upper = 15
Prepared by 11
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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
def isPalindrome(s):
return s == s[::-1] What is a Palindrome?
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
Prepared by 12
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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
Prepared by 13
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
c) Functions: Passing parameters to a Function, Variable Number of
Arguments, Scope, and Passing Functions to a Function
Explanation – Python Functions
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
Prepared by 14
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
Explanation – b. Variable Number of Arguments
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
Prepared by 15
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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
Prepared by 16
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
Program 4
d) Create a list and perform the following methods
1) insert () 2) remove() 3) append() 4) len() 5) pop() 6)clear()
e) Create a dictionary and apply the following methods
1) Print the dictionary items 2) access items 3) useget () 4) change values 5) use
len()
f) Create a tuple and perform the following methods
1) Add items 2) len() 3) check for item in tuple 4)Access items
print("Create a list")
thislist = ["apple", "banana", "cherry"]
print(thislist)
print("Remove an item")
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Prepared by 17
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
print("Remove an item at a specified index")
thislist = ["apple", "banana", "cherry"]
del thislist[0]
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
Prepared by 18
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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
Prepared by 19
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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
Prepared by 20
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
banana
Prepared by 21
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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("John", 36)
print(p1.name)
print(p1.age)
OUTPUT
John
36
Prepared by 22
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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.
Prepared by 23
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
#Open the file "demofile2.txt" and append content to the file:
f = open("itworkshop.txt", "a")
f.write("Now the file has more content!")
f.close()
# 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 ']
Prepared by 24
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
def new (cls):
print("Creating instance")
return super(A, cls). new (cls)
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()
Prepared by 25
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
OUTPUT:
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?
Prepared by 26
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
^a...s$ abs No match
alias Match
abys 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
Prepared by 27
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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.
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.
Prepared by 28
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
Source Code - # Program to extract numbers from a string using RegEx. (re.findall())
#Example 1: re.findall()
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()
Prepared by 29
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
# multiline string
string = 'abc 12\
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
c) 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:
Prepared by 30
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
#The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
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("John", 36)
p1.myfunc()
print(p1.age)
OUTPUT
Prepared by 31
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
Program 6
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))
#Lambda functions can take any number of arguments: Addition argument a with
argument b and return the result:
x = lambda a, b : a + b
print(x(5, 6))
OUTPUT
10
11
Prepared by 32
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
c) 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))
Prepared by 33
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
elif choice == '2':
print(num1, "-", num2, "=", subtract(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
Prepared by 34
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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
#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']
Prepared by 35
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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
Prepared by 36
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
c) Source Code - Python program to sort the elements of an array in
ascending order and Descending order
#Initialize array
arr = [5, 2, 8, 7, 1]
temp = 0;
print(arr[i],end = "")
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
print()
print(arr[i])
Prepared by 37
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
for i in range(0, len(arr)):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
print()
print(arr[i])
Output
52871
8 ******************
Prepared by 38
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
Program 8
c) Write a python program to open a file and check what are the access permissions
acquired by that file using os module.
d) 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")
Rename File
Syntax
Prepared by 39
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
rename(current-name, new-name)
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”)
Prepared by 40
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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
Prepared by 41
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
54
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
Prepared by 42
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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.
print("\n*********Addition*********")
import numpy as np
print(newarr)
Prepared by 43
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
print("\n*********Subtraction*********")
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
Prepared by 44
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
arr1 = np.array([10, 20, 30, 40, 50, 60])
print(newarr)
Output
*********Addition*********
[30 32 34 36 38 40]
*********Subtraction*********
[-10 -1 8 17 26 35]
*********Multiplication*********
*********Division*********
*********Power*********
Prepared by 45
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
b) Explanation of –SciPy Module
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.
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
Prepared by 46
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
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
Prepared by 47
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
Program10
Introduction to basic concept of GUI Programming and Develop desktop based
application with python basic Tkinter() Module.
# Execute Tkinter
Prepared by 48
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
root.mainloop()
Output
Prepared by 49
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
Program 11
Write a python program to create a package (college),sub package (all
dept),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",
"rollno":502,
Prepared by 50
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
"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}
Prepared by 51
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
Program 12
Write a python program to create a package (Engg), sub package(
years),modules (sem) and create 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)
Prepared by 52
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids
Python Programming Lab Manual
#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}}
Prepared by 53
Dr.Md.Fakhruddin H.N - Professor - Methodist College of Engineering & Technology - Abids