[go: up one dir, main page]

0% found this document useful (0 votes)
3 views29 pages

Paython Lab Manual (EX-406) Lab Manual-pages-1

The document is a lab manual for a Computer Science & Engineering course, detailing various Python programming experiments for the academic year 2023-24. It includes a list of experiments covering installation of Python IDE, basic programming concepts, operators, conditional statements, loops, and data structures like lists, tuples, sets, and dictionaries. Each experiment outlines practical significance, theoretical background, and example codes to facilitate learning Python programming.

Uploaded by

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

Paython Lab Manual (EX-406) Lab Manual-pages-1

The document is a lab manual for a Computer Science & Engineering course, detailing various Python programming experiments for the academic year 2023-24. It includes a list of experiments covering installation of Python IDE, basic programming concepts, operators, conditional statements, loops, and data structures like lists, tuples, sets, and dictionaries. Each experiment outlines practical significance, theoretical background, and example codes to facilitate learning Python programming.

Uploaded by

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

JIT BORAWAN

COMPUTER SCIENCE & ENGINEERING


DEPARTMENT

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

12 Write Python program to demonstrate use of:


a) Builtin module (e.g. keyword, math, number, operator)
b) user defined module.

14 Write Python program to demonstrate use of:


a) built-in packages (e.g. NumPy, Pandas) b) user defined packages
Experiment No. 1

Install and configure Python IDE

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

Fig.1: Python release versions


Open the Python 3.7.1 version pack and double click on it to start installation
and installation windows will be open as shown in Fig. 2.

Fig. 2: Installation Type


Click on next install now for installation and then Setup progress windows
will be opened as shown in Fig. 3.
Fig. 3: Setup Progress

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.

2) Starting Python IDLE


Press start button and click on IDLE (Python 3.7 32 bit)
options. You will see the Python interactive prompt i.e.
interactive shell.
Python interactive shell prompt contains opening message >>>, called shell
prompt. A cursor is waiting for the command. A complete command is called a
statement. When you write a command and press enter, the Python interpreter
will immediately display the result.
Experiment No. 2

Write simple Python program to display message on screen

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!

Script Mode Programming


Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is
no longer active.

Let us write a simple Python program in a script. Python files have


extension .py. Type the following source code in a test.py file:

print "Hello, Python!"

We assume that you have Python interpreter set in PATH variable. Now, try
to run this program as follows:

$ Python test.py

This produces the following result:

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!"

We assume that you have Python interpreter available in /usr/bin directory.


Now, try to run this program as follows:

$ chmod +x test.py # This is to make file executable

$./test.py
This produces the following
result – Hello, Python!
Experiment No. 3

Write simple Python program using operators: Arithmetic Operators,


Logical Operators, Bitwise Operators

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

Arithmetic Operators: Arithmetic operators are used to perform mathematical


operations like addition, subtraction, multiplication, division, %modulus, exponent
etc.
Operator Meaning Description Example
Output Addition : Adds the value of the left
and right operands
>>>1+4
5

Subtraction: Subtracts the value of the right operand from the value of the left
operand
>>>10-5
5

Multiplication: Multiplies the value of the left and right operand


>>>5*
2 10

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

Floor Division: Division of operands where the solution is a quotient left


after removing decimal numbers
>>>17//
53

Logical Operators: Logical operators perform Logical AND, Logical OR and


Logical NOT operations. For logical operators following condition are applied.
For AND operator – It returns TRUE if both the operands (right side and
left side) are true
For OR operator- It returns TRUE if either of the operand (right side or left
side) is true
For NOT operator- returns TRUE if operand is false

Operator Meaning Description Example Output


Logical AND: If both the operands are true then condition becomes true.
>>>(8>9) and (2<9)
>>>(9>8)and(2<9)
Fals
e
Tru
e

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

a) IF Statement: if statement is the simplest decision making statement. It is used


to decide whether a certain statement or block of statements will be executed or
not i.e if a certain condition is true then a block of statement is executed otherwise
not.

Syntax:
If condition:
Statement(s)

Example:
i=10
if(i > 20):
print ("10 is less than
20") print ("We are
Not in if ")

Output: We are Not in if

b) If-else Statement: The if statement alone tells us that if a condition is true it


will execute a block of statements and if the condition is false it won’t. But what
if we want to do something else if the condition is false. Here comes the else
statement. We can use the else statement with if statement to execute a block of
code when the condition is false.

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

Write Python program to demonstrate use of looping statements: ‘while’


loop, ‘for’ loop and Nested loop

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

A loop statement allows us to execute a statement or group of statements multiple


times. Python programming language provides following types of loops to handle
looping requirements.

a) while loop: A while loop statement in Python programming language


repeatedly executes a target statement as long as a given condition is true.

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

print 'Current Letter :', letter


fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"

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

Write Python program to perform following operations on Lists: Create


list, Access list, Update list (Add item, Remove item), Delete list

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.

a) Creating List: Creating a list is as simple as putting different comma-separated values


between square brackets.

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[0]=60 #Updating first item


[60,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]

>>> del list[2]

>>> 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

Write Python program to perform following operations on Tuples: Create


Tuple, Access Tuple, Update Tuple, and Delete Tuple
Practical Significance
Like list python supports new tuple as a distinct structure. Tuple are use to store sequence of
python objects which are static in nature. A tuple is immutable which means it cannot be
changed. Just like a list, a tuple contains a sequence of objects in order but once created a
tuple, it cannot be changed anything about it.

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.

a) Creating a Tuple: Creating a tuple is as simple as putting different comma separated


values. Optionally you can put these comma-separated values between parentheses also.

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.

b) Accessing Values in Tuples


To access values in tuple, use the square brackets for slicing along with the index or indices
to obtain value available at that index.

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

Write Python program to perform following operations on Set: Create Set,


Access Set elements, Update Set, Delete Set
Practical Significance
A set is an unordered collection of items. Every element is unique (no duplicates) and must
be immutable (which cannot be changed). A set is created by placing all the items (elements)
inside curly braces {}, separated by comma or by using the built-in function set(). It can have
any number of items and they may be of different types (integer, float, tuple, string etc.). This
practical will make students to work on Set data structure supported in Python.

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}

d) Removing items in set:


We can remove elements from a set by using discard() method. There is no specific index
attached to the newly added element.

Example:
Num=set([10,20,30,40,50])
Num.discard(50)
Print(Num)

Output:
{10,20,30,40}
Experiment No. 9

Write Python program to perform following operations on Dictionaries:


Create Dictionary, Access Dictionary elements, Update Dictionary, Delete
Dictionary, Looping through Dictionary
Practical Significance
As Java supports hash-map, Python supports Dictionary data structure. This data structure
will let user store a data with in a form of key value pair. In this a key is immutable and value
can be any python object which can store any data. One can find relation between key and
value which can get desired value. The dictionary is the data type in Python which can
simulate the real-life data arrangement where some specific value exists for some particular
key. This practical will enable student to work on dictionary and demonstrate work of key
value pair.

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.

a) Creating the Dictionary


The dictionary can be created by using multiple key-value pairs enclosed with the small
brackets () and separated by the colon (:). The collections of the key-value pairs are enclosed
within the curly braces {}.

The syntax to define the dictionary is given below.

#!/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

for key, values in dictionary.items():


print(key)

1. What is the output of the following program?


dictionary1 = {'Google' : 1,
'Facebook' : 2,
'Microsoft' : 3
}
dictionary2 = {'GFG' : 1,
'Microsoft' : 2,
'Youtube' : 3
}
dictionary1.update(dictionary2);
for key, values in dictionary1.items():
print(key, values)
Experiment No. 10

Write Python program to demonstrate math built-in functions


Write Python program to demonstrate string built-in functions
Practical Significance
Like any other 3rd generation language, Python also supports in-built functions to perform
some traditional operations on String and Numbers. The math module is used to access
mathematical functions in the Python. All methods of these functions are used for integer or
real type objects, not for complex numbers. The math module is a standard module in Python
and is always available. To use mathematical functions under this module, you have to import
the module using import math. String functions will let user to develop a code using basic
and advance functions which works on string. This practical will let learner to use
mathematical and string related functions.

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

String build-in functions:


Python includes the following built-in methods to manipulate strings:

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

Develop user defined Python function for given problem:


Function with minimum 2 arguments
Function returning values
Practical Significance
All object oriented programming languages supports reusability. One way to achieve this is to
create a function. Like any other programming languages Python supports creation of
functions and which can be called within program or outside program. Reusability and
Modularity to the Python program can be provided by a function by calling it multiple times.
This practical will make learner use of modularized programming using functions.

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

Write Python program to demonstrate use of:


a) Built-in module (e.g. keyword, math, number, operator)
b) User defined module

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')

b) Python - Math Module


Some of the most popular mathematical functions are defined in the math module. These
include trigonometric functions, representation functions, logarithmic functions, angle
conversion functions, etc. In addition, two mathematical pie and Euler's number constants are
also defined in this module.

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")

d) Python - Random Module


Functions in the random module depend on a pseudo-random number generator function
random(), which generates a random float number between 0.0 and 1.0.
Example
>>>import random
>>>random.random()
0.645173684807533

e) User-defined Module
The user-defined module is written by the user at the time of program writing.

i) Creation a User-defined Module


To create a module just write a Python code in a file with file extension as.py:

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)

ii) Accessing a User-defined Module


Now we will access the module that we created earlier, by using the import statement.

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)

You might also like