Paython Lab Manual (EX-406) Lab Manual-pages-1
Paython Lab Manual (EX-406) Lab Manual-pages-1
LAB MANUAL
(2023-24)
EX-406
Computer programming
*List of Experiment*
S. No. Experiment
1 Install and configure Python IDE
2 Write simple Python program to display message on screen
3 Write simple Python program using operators:
a) Arithmetic Operators b) Logical Operators c) Bitwise Operators
4 Write simple Python program to demonstrate use of conditional
statements:
a) ‘if’ statement b) ‘if … else’ statement c) Nested ‘if’ statement
5 Write Python program to demonstrate use of looping statements:
a) ‘while’ loop b) ‘for’ loop c) Nested loops
6 Write Python program to perform following operations on Lists:
a) Create list b) Access list
c) Update list (Add item, Remove item) d) Delete list
7 Write Python program to perform following operations on Tuples:
a) Create Tuple b) Access Tuple c) Update Tuple d)
Delete Tuple
8 Write Python program to perform following operations on Tuples:
a) Create Set b) Access Set elements c) Update Set d) Delete Set
9 Write Python program to perform following operations on Dictionaries:
a) Create Dictionary b) Access Dictionary elements c) Update
Dictionary
d) Delete Set e) Looping through Dictionary
10 a) Write Python program to demonstrate math built- in functions.
b) Write Python program to demonstrate string built – in functions
11 Develop user defined Python function for given problem:
a) Function with minimum 2 arguments
b) Function returning values
Practical Significance
Python is a high-level, general-purpose, interpreted, interactive, object-oriented
dynamic programming language. Student will able to select and install appropriate
installer for Python in windows and package manager for Linux in order to setup
Python environment for running programs.
Theoretical Background
Python was created by Guido van Rossum during 1985- 1990. Like Perl, Python
source code is also available under the GNU General Public License (GPL).
Python is named after a TV Show called ‘Monty Python’s Flying Circus’ and not
after Python the snake.
Installing Python in Windows:
Open any internet browser. Type http:///www.Python.org/downloads/ in
address bar and Enter.
Click on download the latest version for windows, which shows latest version
as shown in Fig. 1
After complete the installation, Click on close button in the windows as shown
Completion Starting
Python in different modes:
1) Starting Python (Command Line)
Press start button
Click on all programs and then click on Python 3.7 (32 bit). You will
see the Python interactive prompt in Python command line.
Python command prompt contains an opening message >>> called command
prompt. The cursor at command prompt waits for to enter Python command. A
complete command is called a statement. For example check first command to
print message.
To exit from the command line of Python, press Ctrl+z followed by Enter
or Enter exit() or quit() and Enter.
Practical Significance
Python is a high level language which is trending in recent past. To make it more
user friendly developers of Python made sure that it can have two modes Viz.
Interactive mode and Script Mode. The Script mode is also known as normal
mode and uses scripted and finished .py files which are run on interpreter whereas
interactive mode supports command line shells. Students will able to understand
how to run programs using Interactive and Script mode.
Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the
following prompt −
Type the following text at the Python prompt and press the Enter –
>>> print "Hello, Python!"
If you are running new version of Python, then you would need to use print
statement with parenthesis as in print ("Hello, Python!"); However, in Python
version 2.4.3, this produces the following result:
Hello, Python!
We assume that you have Python interpreter set in PATH variable. Now, try
to run this program as follows:
$ Python test.py
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file:
#!/usr/bin/Python
print "Hello, Python!"
$./test.py
This produces the following
result – Hello, Python!
Experiment No. 3
Practical Significance
Operators are used to perform operations on values and variables. Operators can
manipulate individual items and returns a result. The data items are referred as
operands or arguments. Operators are either represented by keywords or special
characters. Here are the types of operators supported by Python:
Arithmetic
Operators
Assignment
Operators
Relational or Comparison
Operators Logical Operators
Bitwise Operators
Identity Operators
Membership
Operators
Theoretical Background
Subtraction: Subtracts the value of the right operand from the value of the left
operand
>>>10-5
5
Division: Divides the value of the left operand by the right operand
>>>10/
25
Exponent: Performs exponential calculation
>>>2**
38
Modulus: Returns the remainder after dividing the left operand with the right
operand
>>>15%4
3
Logical OR : If any of the two operands are non-zero then condition becomes
true.
>>>(2==2) or (9<20)
>>>(3!=3) or (9>20)
Tru
e
Fals
e
Logical NOT: Used to reverse the logical state of its operand.
>>>not(8>2)
>>>not (2 > 10)
Fals
e
Tru
Bitwise Operators: Bitwise operators acts on bits and performs bit by
bit operation. If a=10 (1010) and b=4 (0100)
Operator Meaning Description Example
Output Bitwise AND:
Operator copies a bit, to the result, if it exists in both operands
>>>(a&
b) 0
Bitwise OR: It copies a bit, if it exists in either operand.
>>>(a|
b) 14
~ Bitwise NOT: It is unary and has the effect of 'flipping' bits.
>>>(~a)
-11
^ Bitwise XOR: It copies the bit, if it is set in one operand but not both.
>>>(a^
b) 14
>> Bitwise right shift: The left operand's value is moved right by the number
of bits specified by the right operand.
>>>(a>>
2) 2
<< Bitwise left : The left operand's value is moved >>>(a<<2) shift left by
the number of bits specified by the right operand.
Experiment No. 4
Write simple Python program to demonstrate use of conditional
statements: if’ statement, ‘if … else’ statement, Nested ‘if’ statement
Practical Significance
Decision making is anticipation of conditions occurring while execution of the
program and specifying actions taken according to the conditions. Decision
structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to
execute if outcome is TRUE or FALSE otherwise
Theoretical Background
Syntax:
If condition:
Statement(s)
Example:
i=10
if(i > 20):
print ("10 is less than
20") print ("We are
Not in if ")
Syntax:
if (condition):
# if Condition is true, Executes
this block else:
# if condition is false, Executes this block
Example:
i=10;
if(i<20):
print ("i is smaller than
20") else:
print ("i is greater than 25")
Output:
i is smaller than 20
c) Nested-if Statement:
A nested if is an if statement that is the target of another if statement. Nested if
statements means an if statement inside another if statement. Yes, Python allows
us to nest if statements within if statements. i.e, we can place an if statement inside
another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2
is true # if Block is end here
# if Block is end here
Example:
i =10
if(i ==10):
# First if
statement if(i <
20):
print ("i is smaller than 20")
# Nested - if statement will only be executed if statement
above is true if (i < 15):
print ("i is smaller than 15
too") else:
print ("i is greater than 15")
Output:
i is smaller than 20
i is smaller than 15 too
Experiment No. 5
Practical Significance
While developing a computer application one need to identify all possible
situation. One situation is to repeat execution of certain code block/ line of code.
Such situation can be taken care by looping system. Like all other high level
programming language, Python also supports all loop structure. To keep a
computer doing useful work we need repetition, looping back over the same
block of code again and again. This practical will describe the different kinds of
loops in Python.
Theoretical Background
Syntax
while expression: statement(s)
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following
the loop.
Example
#!/usr/bin/Python
count = 0
while (count < 5):
print 'The count is ', count
count = count + 1
print "Good bye!"
Output:
The count is 0
The count is 1
The count is 2
The count is 3
The count is 4
Good bye!
b) for loop: It has the ability to iterate over the items of any sequence, such as a list or a
string.
Syntax
for iterating_var in sequence: statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence
is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each
item in the list is assigned to iterating_var, and the statement(s) block is executed until the
entire sequence is exhausted.
Example
#!/usr/bin/Python
for letter in 'Python': # First Example
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
c) nested loops: Python programming language allows to use one loop inside another loop.
Following section shows few examples to illustrate the concept.
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as follows –
while expression:
while expression: statement(s)
statement(s)
A final note on loop nesting is that you can put any type of loop inside of any other type of
loop. For example a for loop can be inside a while loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100
#!/usr/bin/Python
i=2
while(i < 20):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1
print "Good bye!"
Output:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
Good bye!
Experiment No. 6
Practical Significance
A list can be defined as a collection of values or items of different types. The items in the list
are separated with the comma (,) and enclosed with the square brackets []. The elements or
items in a list can be accessed by their positions i.e. indices. This practical will make student
acquainted with use of list and operations on list in Python.
Theoretical Background
A list is a collection which is ordered and changeable.
A list is a collection of items or elements; the sequence of data in a list is ordered.
The elements or items in a list can be accessed by their positions i.e. indices
In Python lists are written with square brackets. A list is created by placing all the items
(elements) inside a square brackets [ ], separated by commas.
Lists are mutable. The value of any element inside the list can be changed at any point of
time.
The index always starts with 0 and ends with n-1, if the list contains n elements.
Example:
>>>List1=[‘Java’,’Python’,’Perl’]
>>>List2=[10,20,30,40,50]
b) Accessing 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.
Example:
>>>List2
[10,20,30,40,50]
>>>List2[1]
20
>>>List2[1:3]
[20,30]
>>>List2[5]
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
List2[5]
IndexError: list index out of range
c) Updating List: You can update single or multiple elements of lists by giving the slice on
the left-hand side of the assignment operator, and you can add to elements in a list with the
append() method.
>>>List2
[10,20,30,40,50]
>>>List2[3:4]=70,80
>>>[60,20,30,70,80,50]
i) We can add one item to a list using append() method or add several items using
extend() method.
>>> list1=[10,20,30]
>>> list1
[10, 20, 30]
>>> list1.append(40)
>>> list1
[10, 20, 30, 40]
>>> list1.extend([60,70])
>>> list1
[10, 20, 30, 40, 60, 70]
ii) We can also use + operator to combine two lists. This is also called concatenation
>>> list1=[10,20,30]
>>> list1
[10, 20, 30]
>>> list1+[40,50,60]
[10, 20, 30, 40, 50, 60]
iii) The * operator repeats a list for the given number of times.
>>> list2 ['A', 'B']
>>> list2 *2
['A', 'B', 'A', 'B']
iv) We can insert one item at a desired location by using the method insert()
>>> list1
[10, 20]
>>> list1.insert(1,30)
>>> list1
[10, 30, 20]
d) Deleting List: To remove a list element, you can use either the del statement if you know
exactly which element(s) you are deleting or the remove() method if you do not know.
i) Del Operator: We can delete one or more items from a list using the keyword del. It can
even delete the list entirely. But it does not store the value for further use.
Example:
>>> list=[10,20,30,40,50]
>>> list
[10, 20, 40, 50]
ii) Remove Operator: We use the remove operator if we know the item that we want to
remove or delete from the list (but not the index)
Example:
>>> list=[10,20,30,40,50]
>>> list.remove(30)
>>> list
[10, 20, 40, 50]
Experiment No. 7
Theoretical Background
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples
use parentheses, whereas lists use square brackets.
Example
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is
only one value.
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
Example:
#!/usr/bin/Python
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
Output:
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
c) Updating Tuples: Tuples are immutable which means you cannot update or change the
values of tuple elements. You are able to take portions of existing tuples to create new tuples.
Example:
#!/usr/bin/Python
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
Output:
(12, 34.56, 'abc', 'xyz')
d) Delete Tuple Elements: Removing individual tuple elements is not possible. There is, of
course, nothing wrong with putting together another tuple with the undesired elements
discarded. To explicitly remove an entire tuple, just use the del statement.
Example:
#!/usr/bin/Python
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
Experiment No. 8
Theoretical Background
Mathematically a set is a collection of items not in any particular order. A Python set is
similar to this mathematical definition with below additional conditions.
The elements in the set cannot be duplicates.
The elements in the set are immutable (cannot be modified) but the set as a whole is
mutable.
There is no index attached to any element in a Python set. So they do not support any
indexing or slicing operation.
The sets in Python are typically used for mathematical operations like union, intersection,
difference and complement etc.
a) Creating a set:
A set is created by using the set() function or placing all the elements within a pair of
curly braces.
Example:
>>> a={1,3,5,4,2}
>>> print("a=",a)
a= {1, 2, 3, 4, 5}
>>> print(type(a))
<class 'set'>
b) Accessing values in a set: We cannot access individual values in a set. We can only
access all the elements together. But we can also get a list of individual elements by looping
through the set.
Example:
Num=set([10,20,30,40,50])
for n in Num:
print(n)
Output:
10
20
30
40
50
c) Updating items in a set: We can add elements to a set by using add() method. There is no
specific index attached to the newly added element.
Example:
Num=set([10,20,30,40,50])
Num.add(60)
print(Num)
Output:
{10,20,30,40,50,60}
Example:
Num=set([10,20,30,40,50])
Num.discard(50)
Print(Num)
Output:
{10,20,30,40}
Experiment No. 9
Theoretical Background
Python dictionary is a container of key-value pairs. It is mutable and can contain mixed types.
A dictionary is an unordered collection. Python dictionaries are called associative arrays or
hash tables in other languages. The keys in a dictionary must be immutable objects like
strings or numbers. They must also be unique within a dictionary.
#!/usr/bin/Python
dict = {'Name': 'Nikhil', 'Age': 28, 'Class': 'First'}
b) Accessing Values in Dictionary: To access dictionary elements, you can use the familiar
square brackets along with the key to obtain its value.
Example:
#!/usr/bin/Python
dict = {'Name': 'Nikhil', 'Age': 28, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
Output:
dict['Name']: NIKHIL
dict['Age']: 28
c) Updating Dictionary: You can update a dictionary by adding a new entry or a key value
pair, modifying an existing entry, or deleting an existing entry.
Example:
#!/usr/bin/Python
dict = {'Name': 'Nikhil', 'Age': 28, 'Class': 'First'}
dict['Age'] = 28; # update existing entry
dict['School'] = "NRI IST"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
Output:
dict['Age']: 28
dict['School']: NRI IST
d) Delete Dictionary Elements: You can either remove individual dictionary elements or
clear the entire contents of a dictionary. You can also delete entire dictionary in a single
operation. To explicitly remove an entire dictionary, just use the del statement.
Example:
#!/usr/bin/Python
dict = {'Name': 'NIKHIL’, 'Age': 17, ‘Sem': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
Looping through Dictionary: A dictionary can be iterated using the for loop. If you want to
get both keys and the values in the output. You just have to add the keys and values as the
argument of the print statement in comma separation. After each iteration of the for loop, you
will get both the keys its relevant values in the output.
Example
dict = {'Name': 'NIKHIL’, 'Age': 17, ‘Sem': 'First'}
for key, value in dict.items():
print(key, ' - ', value)
The above example contains both the keys and the values in the output. The text
‘Related to’ in the output showing the given key is related to the given value in the
output.
Name - NIKHIL
Age - 17
Sem - First
Theoretical Background
Math’s built-in Functions: Here is the list of all the functions and attributes defined in math
module
Function Description
ceil(x) Return the Ceiling value. It is the smallest integer, greater or equal
to the number x.
copysign(x, y) Returns x with the sign of y
cos(x) Return the cosine of x in radians
exp(x) Returns e**x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
gcd(x, y) Returns the Greatest Common Divisor of x and y
log(x[, base]) Returns the Log of x, where base is given. The default base is e
log2(x) Returns the Log of x, where base is 2
log10(x) Returns the Log of x, where base is 10
pow(x, y) Return the x to the power y value.
remainder(x, y) Find remainder after dividing x by y.
radians(x) Convert angle x from degrees to radian
sqrt(x) Finds the square root of x
sin(x) Return the sine of x in radians
tan(x) Return the tangent of x in radians
Function Description
capitalize() Converts the first character to upper case
count() Returns the number of times a specified value occurs in a string
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was found
index() Searches the string for a specified value and returns the position of where it was
found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdigit() Returns True if all characters in the string are digits
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isspace() Returns True if all characters in the string are whitespaces
isupper() Returns True if all characters in the string are upper case lower() Converts a string
into lower case
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was
found
rindex() Searches the string for a specified value and returns the last position of where it was
found
split() Splits the string at the specified separator, and returns a list
Strip() Remove spaces at the beginning and at the end of the string:
startswith() Returns true if the string starts with the specified value
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
Experiment No. 11
Practical Skills
Develop general purpose programming using Python to solve problem.
The practical is expected to develop the following skills:
Write a Python Program using function that will accept 2 arguments
Write a Python Program using function that will return a value
Theoretical Background
Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code which can be called whenever required.
a) Creating a function: In Python, we can use def keyword to define the function.
Syntax:
def my_function():
function-suite
return <expression>
b) Calling a function: To call the function, use the function name followed by the
parentheses.
def hello_world():
print("hello world")
hello_world()
Output:
hello world
c) Arguments in function: The information into the functions can be passed as the
argumenta. The arguments are specified in the parentheses. We can give any number of
arguments, but we have to separate them with a comma.
Example
#defining the function
def func (name):
print("Hi ",name);
#calling the function
func("ABC")
Output:
hi ABC
d) return Statement: The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no arguments is the same as return
None.
Example
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function: ", total
return total;
# Now you can call sum function
total = sum(10, 20 );
print "Outside the function: ", total
Output:
Outside the function: 30
Experiment No. 12
Practical Significance
While developing a computer application, more often than not the line of code (LOC) can go
beyond developer’s control. Such codes are tightly coupled and hence are difficult to manage.
Also one cannot reuse such code in other similar application. Python supports modularized
coding which allow developers to write a code in smaller blocks. A module can define
functions, classes and variables. A module can also include runnable code. By using module
students will be able to group related code that will make the code easier for them to understand
and use.
Theoretical Background
a) Built-in Modules
Built-in modules are written in C and integrated with the Python interpreter. Each built-in
module contains resources for certain system-specific functionalities such as OS
management, disk IO, keyword, math, number, operator etc. The standard library also
contains many Python scripts (with the .py extension) containing useful utilities. To display a
list of all available modules, use the following command in the Python console:
>>> help('modules')
Example
>>> import math
>>>math.pi
3.141592653589793
c) Python - OS Module
It is possible to automatically perform many operating system tasks. The OS module in Python
provides functions for creating and removing a directory (folder), fetching its contents,
changing and identifying the current directory, etc.
Example
We can create a new directory using the mkdir() function from the OS module.
>>> import os
>>>os.mkdir("d:\\tempdir")
e) User-defined Module
The user-defined module is written by the user at the time of program writing.
Example
A module in a file with extension as module_name.py in Python is created.
def accept_int():
val = int(input("Please enter any integer integer: "))
print('The integer value is', val)
Example
import the module in Python.
import module_name
Output
Please enter any integer integer: 22
The integer value is 22
import time
print time.time()
print date.fromtimestamp(454554)