PYTHON Lab Manual1
PYTHON Lab Manual1
PYTHON
PROGRAMMING
LAB
INDEX OF EXPERIMENTS
Week Theory/ Practical (Group-I/ II) Topic Covered Date and
Remarks
1
Mandatory instructions for students:
1. Students should report to the concerned labs as per the given timetable.
2. Students should make an entry in the log book whenever they enter the labs during
practical or for their own personal work.
3. When the experiment is completed, students should shut down the computers and make
the counter entry in the logbook.
4. Any damage to the lab computers will be viewed seriously.
5. Students should not leave the lab without concerned faculty’s permission.
2
Assignment: 1
Prerequisites
You should have a basic understanding of Computer Programming terminologies. A basic
understanding of any of the programming languages is a plus.
• Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
3
Python Features
Python's features include −
• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
• Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
• GUI Programming − Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and
the X Window system of Unix.
• Scalable − Python provides a better structure and support for large programs than shell
scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listed
below −
• It can be used as a scripting language or can be compiled to byte-code for building large
applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
4
First Python Program:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
A Python variable is a reserved memory location to store values. In other words, a variable in a
python program gives data to the computer for processing.
Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple,
Strings, Dictionary, etc. Variables can be declared by any name or even alphabets like a, aa, abc, etc.
Let see an example. We will declare variable "a" and print it.
a=100
print a
5
Python 1 Example
Python 2 Example
x = 123 # integer
x = "hello" # string
x = [0,1,2] # list
x = (0,1,2) # tuple
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants
as containers that hold information which cannot be changed later.
Non technically, you can think of constant as a bag to store some books and those books cannot
be replaced once place inside the bag.
6
Assigning value to a constant in Python
In Python, constants are usually declared and assigned on a module. Here, the module means a
new file containing variables, functions etc which is imported to main file. Inside the module,
constants are written in all capital letters and underscores separating the words.
Create a constant.py
1. PI = 3.14
2. GRAVITY = 9.8
Create a main.py
1. import constant
2.
3. print(constant.PI)
4. print(constant.GRAVITY)
When you run the program, the output will be:
3.14
9.8
Types of Operator
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Let us have a look on all operators one by one.
7
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −
- Subtraction Subtracts right hand operand from left hand operand. a–b=
10
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
//
Floor Division - The division of operands where the result is 9//2 = 4
the quotient in which the digits after the decimal point are and
8
removed. But if one of the operands is negative, the result is 9.0//2.0
floored, i.e., rounded away from zero (towards negative = 4.0,
infinity) − 11//3 =
-4, -
11.0//3
= -4.0
[ Show Example ]
<> If values of two operands are not equal, then condition becomes (a <> b) is
true. true. This
is similar
to
!=
operator.
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
9
< If the value of left operand is less than the value of right operand, (a < b) is
then condition becomes true. true.
>= If the value of left operand is greater than or equal to the value of (a >= b) is
right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value of (a <= b) is
right operand, then condition becomes true. true.
[ Show Example ]
= Assigns values from right side operands to left side operand c=a+b
assigns
value of a
+ b into c
+= Add AND It adds right operand to the left operand and assign the c += a is
result to left operand equivalent
to c = c +
a
-= Subtract It subtracts right operand from the left operand and assign c -= a is
AND the result to left operand equivalent
to c = c - a
10
*= Multiply It multiplies right operand with the left operand and assign
AND the result to left operand c *= a is
equivalent
to c = c * a
/= Divide AND It divides left operand with the right operand and assign the c /= a is
result to left operand equivalent
to c = c /
ac /= a is
equivalent
to c = c / a
%= Modulus It takes modulus using two operands and assign the result to c %= a is
AND left operand equivalent
to c = c % a
//= Floor It performs floor division on operators and assign value to c //= a is
Division the left operand equivalent
to c = c //
a
11
a&b = 0000 1100
= 0011 0001
~a = 1100 0011
[ Show Example ]
& Binary AND Operator copies a bit to the result if it exists in both (a & b)
operands (means
0000 1100)
^ Binary XOR It copies the bit if it is set in one operand but not (a ^ b) = 49
both. (means
0011 0001)
~ Binary Ones It is unary and has the effect of 'flipping' bits. (~a ) = -61
Complement (means 1100
0011
in 2's
complement
form due to
a signed
binary
number.
12
<< Binary Left Shift The left operands value is moved left by the number a << 2 = 240
of bits specified by the right operand. (means
1111 0000)
>> Binary Right Shift The left operands value is moved right by the a >> 2 = 15
number of bits specified by the right operand. (means
0000 1111)
[ Show Example ]
Operator Description Example
and Logical If both the operands are true then condition becomes true. (a and
AND b) is
true.
not Logical Used to reverse the logical state of its operand. Not(a
NOT and b) is
false.
[ Show Example ]
13
Operator Description Example
a 1 if x is
a
member
of
sequence
y.
not in Evaluates to true if it does not finds a variable in the specified x not in y,
sequence and false otherwise. here not
in results
in
a 1 if x is
not a
member
of
sequence
y.
[ Show Example ]
Operator Description Example
14
Is Evaluates to true if the variables on either side of the operator x is y, here is
point to the same object and false otherwise. results in 1 if
id(x) equals
id(y).
not equal to
id(y).
[ Show Example ]
**
1 Exponentiation (raise to the power)
~+-
2
Complement, unary plus and minus (method names for the last two are +@ and -
@)
* / % //
3
Multiply, divide, modulo and floor division
+-
4 Addition and subtraction
>> <<
5
Right and left bitwise shift
&
6
Bitwise 'AND'
^|
7
Bitwise exclusive `OR' and regular `OR'
<= < > >=
8
Comparison operators
<> == !=
9
Equality operators
= %= /= //= -= += *= **=
10
Assignment operators
Is, is not
11
Identity operators
In, not in
12
Membership operators
not, or, and
13 Logical operators
Exercise:
1. WAP to add two numbers in python
2. WAP to declare variables and display types of respective variables
3. WAP to demonstrate type casting in python
4. WAP to demonstrate Logical operators
Assignment 2
Theory:
String Literals
String literals in python are surrounded by either single quotation marks, or double quotation marks.
Example
print("Hello") print('Hello')
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
Example
a = "Hello"
print(a)
Multiline Strings
Like many other popular programming languages, strings in Python are arrays of bytes representing
unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length
of 1. Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Example
b = "Hello, World!"
print(b[2:5])
Exercise:
1. WAP to Calculate length of string
2. WAP to make string from 1st two and last two characters from given string.
3. WAP to concatenate two strings
Assignment: 3
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.
Following is the general form of a typical decision making structure found in most of the
programming languages −
Python programming language assumes any non-zero and non-null values as TRUE, and if it is
either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements. Click the
following links to check their detail.
Sr.No. Statement & Description
if statements
1
Exercise:
1. WAP to find out greatest of 3 numbers
2. WAP to find whether given number is odd or even
3. Write a C program to check whether a character is uppercase or lowercasealphabet.
4. WAP to find whether given input is number or character
Assignment: 4
Theory:
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. There may be a situation when you need to execute a
block of code several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The
following diagram illustrates a loop statement −
Python programming language provides following types of loops to handle looping requirements.
1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests
the condition before executing the loop body.
for loop
2
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
nested loops
3
You can use one or more loop inside any another while, for or do..while loop.
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their detail.
Let us go through the loop control statements briefly
1
break statement
2
continue statement
Causes the loop to skip the remainder of its body and immediately retest itscondition
prior to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntacticallybut you
do not want any command or code to execute.
Exercise:
An array is a special variable, which can hold more than one value at a time. If you have a list of
items (a list of car names, for example), storing the cars in single variables could look like this:
However, what if you want to loop through the cars and find a specific one? And what if you had
not 3 cars, but 300?
An array can hold many values under a single name, and you can access the values by referring to
an index number.
x = cars[0]
Example
cars[0] = "Toyota"
x = len(cars)
Note: The length of an array is always one more than the highest array index.
You can use the for in loop to loop through all the elements of an array.
Example
for x in cars:
print(x)
cars.append("Honda")
You can use the pop() method to remove an element from the array.
Example
cars.pop(1)
You can also use the remove() method to remove an element from the array.
Example
cars.remove("Volvo")
Note: The remove() method only removes the first occurrence of the specified value.
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
insert() Adds an element at the specified position
Python List:
The list is a most versatile datatype available in Python which can be written as a list of
commaseparated values (items) between square brackets. Important thing about a list is that
items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square brackets.
For example −
1
cmp(list1, list2)
2
len(list)
Gives the total length of the list.
3
max(list)
Returns item from the list with max value.
4
min(list)
Returns item from the list with min value.
5
list(seq)
Converts a tuple into list.
Python includes following list methods
Sr.No. Methods with Description
1 list.append(obj)
2
list.count(obj)
Returns count of how many times obj occurs in list
3
list.extend(seq)
Appends the contents of seq to list
4
list.index(obj)
Returns the lowest index in list that obj appears
5
list.insert(index, obj)
Inserts object obj into list at offset index
6
list.pop(obj=list[-1])
Removes and returns last object or obj from list
7
list.remove(obj)
Removes object obj from list
8
list.reverse()
Reverses objects of list in place
9
list.sort([func])
Sorts objects of list, use compare func if given
Python Tuple:
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.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put
these comma-separated values between parentheses also. For example −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
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. For example −
= ('abc', 'xyz');
# tup1[0] = 100;
tup3;
tup = ('physics', 'chemistry', 1997, 2000); print tup; del tup; print "After
This produces the following result. Note an exception raised, this is because after del tup tuple
does not exist any more −
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols, i.e.,
brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short
examples −
x,y;
1
cmp(tuple1, tuple2)
2
len(tuple)
Gives the total length of the tuple.
3
max(tuple)
Returns item from the tuple with max value.
4
min(tuple)
Returns item from the tuple with min value.
5
tuple(seq)
Converts a list into tuple.
Python Sets:
A set is a collection which is unordered and unindexed. In Python sets are written with curly
brackets.
Example
Create a Set:
Note: Sets are unordered, so the items will appear in a random order.
Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has
no index.
But you can loop through the set items using a for loop, or ask if a specified value is present in a
set, by using thein keyword.
Example
for x in thisset:
print(x)
Example
print("banana" in thisset)
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add more than one item to a set use the update() method.
Example
thisset.add("orange")
print(thisset)
Example
print(thisset)
Get the Length of a Set
To determine how many items a set has, use the len() method.
Example
print(len(thisset)
Remove Item
thisset.remove("banana")
print(thisset)
Note: If the item to remove does not exist, remove() will raise an error.
Example
thisset.discard("banana")
print(thisset)
Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use thepop(), method to remove an item, but this method will remove item.
the last ts are unordered, so you will not know what item that gets
removed.
The return value of the pop() method is the removed item.
Example
x = thisset.pop()
print(x) print(thisset)
Note: Sets are unordered, so when using the pop() method, you will not know which item that
gets removed.
Example
thisset.clear()
print(thisset)
Example
del thisset
print(thisset)
Dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
x = thisdict["model"]
There is also a method called get() that will give you the same result:
Example
x = thisdict.get("model")
Exercise:
1. Write a Python script to sort (ascending and descending) a dictionary by value
2. Write a Python script to check if a given key already exists in a dictionary.
3. Write a Python script to merge two Python dictionaries
4. Write a Python program to add an item in a tuple.
5. Write a Python program to create a tuple with different data types
6. Write a Python program to sum all the items in a list
7. Write a Python program to get the largest number from a list.
8. Write a Python program to add member(s) in a set.
9. Write a Python program to reverse the order of the items in the array
10. Write a Python program to create an array of 5 integers and display the array items. Accessindividual
element through indexes.
Assignment:6
Aim: To study functions in python
Theory:
A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result.
Creating a Function
Example
Example
Parameters
Information can be passed to functions as parameter. Parameters are specified after the function
name, inside the parentheses. You can add as many parameters as you want, just separate them
with a comma.The following example has a function with one parameter (fname). When the
function is called, we pass along a first name, which is used inside the function to print the full
name:
Example
my_function("Emil") my_function("Tobias")
my_function("Linus") Default Parameter
Value
The following example shows how to use a default parameter value. If we call the function
without parameter, it uses the default value:
Example
my_function("Sweden")
my_function("India") my_function()
my_function("Brazil")
You can send any data types of parameter to a function (string, number, list, dictionary etc.), and
it will be treated as the same data type inside the function. E.g. if you send a List as a parameter,
it will still be a List when it reaches the function:
Example
my_function(fruits)
Return Values
Example
def my_function(x):
return 5 * x
print(my_function(3)) print(my_function(5))
print(my_function(9)) 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 developer should be very careful with recursion as it can be quite easy to slip into writing a
function which never terminates, or one that uses excess amounts of memory or processor
power. However, when written correctly recursion can be a very efficient and
mathematicallyelegant approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use
the k variable as the data, which decrements-1) every time we recurse. The recursion ends when
To a new developer it can take some time to work out how exactly this works, best way to find
out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else: result
=0
return result
Exercise:
iii. Alter: Used to add, delete or change data type of column of table. Syn: alter
table table_name add column column_name type; alter table
table_name drop column column name; alter table table_name alter
column column name type; ex: alter table syit add column address
varchar(10); alter table syit drop address;
alter table syit alter column name varchar(10);
iv. Truncate: Used to delete contents of table but it will preserve structure of
table
Syn: truncate table table_name ;
Ex: truncate table syit;
Exercise:
Assignment: 8
What is PyMySQL ?
PyMySQL is an interface for connecting to a MySQL database server from Python. It implements
the Python Database API v2.0 and contains a pure-Python MySQL client library. The goal of
PyMySQL is to be a drop-in replacement for MySQLdb.
import pymysql
If it produces the following result, then it means MySQLdb module is not installed −
$ cd PyMySQL*
Note − Make sure you have root privilege to install the above module.
Database Connection
Before connecting to a MySQL database, make sure of the following points −
• This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
Example
Following is an example of connecting with MySQL database "TESTDB" −
import pymysql
pymysql.connect("localhost","testuser","test123","TESTDB" )
= db.cursor()
cursor.execute("SELECT VERSION()")
Example
Let us create a Database table EMPLOYEE −
import pymysql
pymysql.connect("localhost","testuser","test123","TESTDB" )
= db.cursor()
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
cursor.execute(sql)
INSERT Operation
The INSERT Operation is required when you want to create your records into a database table.
Example
The following example, executes SQL INSERT statement to create a record in the EMPLOYEE table
−
import pymysql
pymysql.connect("localhost","testuser","test123","TESTDB" )
= db.cursor()
try:
Example
The following code segment is another form of execution where you can pass parameters directly
−
..................................
user_id = "test123"
password = "password"
READ Operation
READ Operation on any database means to fetch some useful information from the database.
Once the database connection is established, you are ready to make a query into this database.
You can use either fetchone() method to fetch a single record or fetchall() method to fetch
multiple values from a database table.
• fetchone() − It fetches the next row of a query result set. A result set is an object that is
returned when a cursor object is used to query a table.
• fetchall() − It fetches all the rows in a result set. If some rows have already been extracted
from the result set, then it retrieves the remaining rows from the result set.
• rowcount − This is a read-only attribute and returns the number of rows that were
affected by an execute() method.
Example
The following procedure queries all the records from EMPLOYEE table having salary more than
1000 −
import pymysql
pymysql.connect("localhost","testuser","test123","TESTDB" )
= db.cursor()
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
= row[3] income
= row[4]
Output
This will produce the following result −
Update Operation
Exercise:
1. Create python application which will accept name and age and store it into mysql
2. Create python application which will display all names and ages from mysql table
3. Write python application to delete all entries with ages 28
Assignment: 9
Theory:
File Handling
The key function for working with files in Python is the open() function.
"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
Syntax
To open a file for reading it is enough to specify the name of the file:
open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.
Hello! Welcome to demofile.txt This file is for testing purposes. Good Luck!
The open() function returns a file object, which has a read() method for reading the content of
the file:
Example
By default the read() method returns the whole text, but you can also specify how many
characters you want to return:
Example
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:
Example
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line:
Example
f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files
It is a good practice to always close the file when you are done with it.
Example
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Note: You should always close your files, in some cases, due to buffering, changes made to a
file may not show until you close the file.
Write to an Existing File
To write to an existing file, you must add a parameter to the open() function:
Example
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Example
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
f = open("myfile.txt", "x")
Exercise:
Theory:
Python Classes/Objects
Create a Class
To create a class, use the keyword class:
Example
class MyClass:
x=5
Create Object
p1 = MyClass()
print(p1.x)
The examples above are classes and objects in their simplest form, and are not really useful in
real life applications.
To understand the meaning of classes we have to understand the built-in init () function.
All classes have a function called init (), which is always executed when the class is being
initiated.
Use the init () function to assign values to object properties, or other operations that are
necessary to do when the object is being created:
Example
Create a class named Person, use the init () function to assign values for name and age:
class Person:
def init (self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name) print(p1.age)
Note: The init () function is called automatically every time the class is being used to create
a new object.
Exercise: