0% found this document useful (0 votes)
11 views58 pages

Python Manual

This document is a laboratory manual for the Python Programming course (IT23202) at Government Polytechnic Mumbai, aimed at developing industry-relevant skills through practical exercises. It outlines the course objectives, practical outcomes, and guidelines for both students and teachers to enhance learning and competency in Python programming. The manual includes a list of practicals, expected skills, and assessment criteria to ensure effective learning and application of programming concepts.

Uploaded by

shanuu2777
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)
11 views58 pages

Python Manual

This document is a laboratory manual for the Python Programming course (IT23202) at Government Polytechnic Mumbai, aimed at developing industry-relevant skills through practical exercises. It outlines the course objectives, practical outcomes, and guidelines for both students and teachers to enhance learning and competency in Python programming. The manual includes a list of practicals, expected skills, and assessment criteria to ensure effective learning and application of programming concepts.

Uploaded by

shanuu2777
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

A Laboratory Manual for

Python Programming
(IT23202)

Semester– IV

Government Polytechnic Mumbai


Department of Information Technology
Government Polytechnic Mumbai

Certificate

This is to certify that Mr. / Ms. ………………………………….

Enrollment No………………………. of Fourth Semester of Diploma


in Information Technology has completed the term work
satisfactorily insubject Python Programming (IT23202) for
the academicyear 20…….to 20…...... as prescribed in the
curriculum.

Place ………………. Enrollment No……………………


Date: ........................ Exam Seat No. ………………......

Subject Teacher Head of the Department Principal


Python Programming (IT23202)

Preface
The primary focus of any engineering laboratory/field work in the technical education
system is to develop the much needed industry relevant competencies and skills. With this
in view, MSBTE embarked on this innovative ‘I’ Scheme curricula for engineering Diploma
programmes with outcome-based education as the focus and accordingly, relatively large
amount of time is allotted for the practical work. This displays the great importance of
laboratory work making each teacher, instructor and student to realize that every minute
of thelaboratory time need to be effectively utilized to develop these outcomes, rather
than doing other mundane activities. Therefore, for the successful implementation of this
outcome-based curriculum, every practical has been designed to serve as a ‘vehicle’ to
develop this industry identified competency in every student. The practical skills are
difficult to develop through ‘chalk and duster’ activity in the classroom situation.
Accordingly, the ‘I’ scheme laboratory manual development team designed the practical’s
to focus on outcomes, rather than the traditional age old practice of conducting practical’s
to ‘verify the theory’ (which may becomea by-product along the way).

This laboratory manual is designed to help all stakeholders, especially the students,
teachers and instructors to develop in the student the pre-determined outcomes. It is
expected fromeach student that at least a day in advance, they have to thoroughly read
the concerned practical procedure that they will do the next day and understand
minimum theoretical background associated with the practical. Every practical in this
manual begins by identifying the competency, industry relevant skills, course outcomes
and practical outcomes which serveas a key focal point for doing the practical. Students
will then become aware about the skills they will achieve through procedure shown there
and necessary precautions to be taken, whichwill help them to apply in solving real-world
problems in their professional life.

This manual also provides guidelines to teachers and instructors to effectively facilitate
student-centered lab activities through each practical exercise by arranging and managing
necessary resources in order that the students follow the procedures and precautions
systematically ensuring the achievement of outcomes in the students.

Python is a high-level, interpreted, reflective, dynamically typed, open source, multi-


paradigmand general purpose programming language. It is quite powerful and easy. It
offers no special tools or features that let you do things that you cannot do with other
languages, but its elegant design and combination of certain features make Python a
pleasure to use.

Although all care has been taken to check for mistakes in this laboratory manual, yet it is
impossible to claim perfection especially as this is the first edition. Any such errors and
suggestions for improvement can be brought to our notice and are highly welcome.

Government Polytechnic Mumbai i


Python Programming (IT23202)

Programme Outcomes (POs) to be achieved through Practical’s of


thisCourse

Following programme outcomes are expected to be achieved significantly out of the ten
programme outcomes and Computer Engineering programme specific outcomes through
the practical’s of the course on Python Programming

PO1 Basic and Discipline specific knowledge: Apply knowledge of basic mathematics, science
and engineering fundamentals and engineering specialization to solve the engineering
problems.
PO2 Problem analysis: Identify and analyze well-defined engineering problems using codified
standard methods.
PO3 Design/ development of solutions: Design solutions for well-defined technical problems
and assist with the design of systems components or processes to meet specified needs.
PO4 Engineering Tools, Experimentation and Testing: Apply modern engineering tools and
appropriate technique to conduct standard tests and measurements.

PO5 Engineering practices for society, sustainability and environment: Apply


appropriate technology in context of society, sustainability, environment and
ethical practices.
PO6 Project Management: Use engineering management principles individually, as a team
member or a leader to manage projects and effectively communicate about well-defined
engineering activities.

PO7 Life-long learning: Ability to analyze individual needs and engage in updating in the
context of technological changes.

Programme Specific Outcomes (PSOs)

PSO1 The student should do programming, database management, networking, web design,
Information Security, Cyber Security and recognize the need for independent and lifelong
learning in the era of fast changing Information technology.
PSO2 The Student should apply knowledge to solve problems through tools with understanding of
social, ethical and environmental context.
PSO3 The student should Analyze Computing problems and find solutions as an individual and can
work in a team as a member or team leader.

Government Polytechnic Mumbai ii


Python Programming (IT23202)

Practical- Course Outcome matrix


Course Outcomes (COs)
CO1 Perform different operation on data structures in python with decision making and
functions
CO2 Apply object oriented concept in python programming.
CO3 Perform file handling with exceptions.
CO4 Validate the fields using regular expression
CO5 Design GUI forms and Database connectivity
Sr. Title of the Practical CO1 CO2 CO3 CO4 CO5
No. e.
[Link] Python IDE . - - -
1 √ -
[Link] basic operations on
different data types
List,Tuple,dictionary,sets,arra
y
Develop program for decision making - - -
2 if…else ,if….elif…else
√ -
For loop,while ,
Develop program for user defined
functions -
[Link] argument - - -
3
[Link] argument √
[Link] argument
[Link] length argument
Develop program for classes and object - √ - - -
4 Private
variable,Encapsulation,constructor,
5 Develop program for Inheritance And - √ - -
polymorphism.
Develop program for file handling and - - √ - -
6 exception handling in python
7 Develop program for Regular Expression - - √ -
8 Develop python program for GUI - - - √
canvas,Frame and draw differ shapes on
it line,rectangle,[Link],
9 Develop python program for GUI Frame √
button,Label,checkbutton,radiobutton,
spinbox,entry ,menubar,Database
Connectivity
10 Mini project √ √ √ √ √

Government Polytechnic Mumbai iii


Python Programming (IT23202)

List of Industry Relevant Skills

The following industry relevant skills of the competency “Develop general purpose
programming using Python to solve problem” are expected to be developed in you by
performing practicals of this laboratory manual.
1. Develop Applications using Python.
2. Write and Execute Python programs using functions, classes and Exception handling

Brief Guidelines to Teachers

Hints regarding strategies to be used


1. Teacher shall explain prior concepts to the students before starting each experiment.
2. For practical’s requiring tools to be used, teacher should provide the
demonstration ofthe practical emphasizing the skills, which the student should
achieve.
3. Involve students in the activities during the conduct of each experiment.
4. Teachers should give opportunity to students for hands-on after the demonstration.
5. Assess the skill achievement of the students and COs of each unit.
6. Teacher is expected to share the skills and competencies to be developed
in thestudents.
7. Teacher should ensure that the respective skills and competencies are developed
in thestudents after the completion of the practical exercise.
8. Teacher may provide additional knowledge and skills to the students even
though thatmay not be covered in the manual but are expected from the students
by the industries.
9. Teacher may suggest the students to refer additional related literature of the
referencebooks/websites/seminar proceedings etc.
10. During assessment teacher is expected to ask questions to the students to
tap theirknowledge and skill related to that practical.

Government Polytechnic Mumbai iv


Python Programming (IT23202)

Instructions for Students

Student shall read the points given below for understanding the theoretical
concepts andpractical applications.
1. Students shall listen carefully the lecture given by teacher about
importance ofsubject, learning structure, course outcomes.
2. Students shall organize the work in the group of two or three members and
make arecord of all observations.
3. Students shall understand the purpose of experiment and its practical
implementation.
4. Students shall write the answers of the questions during practical.
5. Student should feel free to discuss any difficulty faced during the
conduct ofpractical.
6. Students shall develop maintenance skills as expected by the industries.
7. Student shall attempt to develop related hands on skills and gain confidence.
8. Students shall refer technical magazines; websites related to the scope of the
subjectsand update their knowledge and skills.
9. Students shall develop self-learning techniques.
10. Students should develop habit to submit the write-ups on the scheduled
dates andtime.

Government Polytechnic Mumbai v


Python Programming (IT23202)

Content Page
List of Practical’s and Progressive Assessment Sheet

Date of Date Assess Remark


S. Dated
Title of the practical perform of ment (if any)
No. [Link]
ance subm marks(10)
ission teacher

1 [Link] Python IDE .


[Link] basic operations on
different data types
List,Tuple,dictionary,sets,array
Develop program for decision
2 making if…else ,if….elif…else
For loop,while ,
3 Develop program for user defined
functions
[Link] argument
[Link] argument
[Link] argument
[Link] length argument
4 Develop program for classes and
object Private variable,
Encapsulation, constructor
5 Develop program for Inheritance
And polymorphism.
Develop program for file handling
6 and exception handling in python
7 Develop program for Regular
Expression
8 Develop python program for GUI
canvas,Frame and draw differ
shapes on it
line,rectangle,[Link],
9 Develop python program for GUI
Frame
button,Label,checkbutton,radiobu
tton, spinbox,entry
,menubar,Database Connectivity
10 Mini project

Total Marks
Total Marks (Scaled to 25 Marks)

Government Polytechnic Mumbai vi


Python Programming (IT19401)

Practical No. 1: Install and configure Python IDE


[Link] basic operations on different data types
List,Tuple,dictionary,sets,array

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

II. Minimum 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 [Link] in
addressbar and Enter.
 Home page of Python will have displayed as shown in Fig. 1

Fig. 1: Home Page


 Click on download the latest version for windows, which shows latest
version asshown in Fig. 2

Government Polytechnic Mumbai 7


Python Programming (IT19401)

Fig.2: Python release versions


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

Fig. 3: Installation Type

 Click on next install now for installation and then Setup progress windows
will beopened as shown in Fig. 4.

Fig. 4: Setup Progress

 After complete the installation, Click on close button in the windows as


shown inFig. 5.

Government Polytechnic Mumbai 8


Python Programming (IT19401)

Fig. 5: Setup

CompletionStarting 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
thePython 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.

Government Polytechnic Mumbai 9


Python Programming (IT19401)

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
Government Polytechnic Mumbai 10
Python Programming (IT19401)

interpreter willimmediately display the result.

III. Practical related Questions


Note: Below given are few sample questions for reference. Teachers must
designmore such questions to ensure the achievement of identified CO.
2. List key features of Python
3. List different built in data types and operations on it.

Dated signature
ofTeacher

Government Polytechnic Mumbai 11


Python Programming (IT19401)

Practical No. 2: Develop program for operators,decision making if…else ,if….elif…else


For loop,while loop ,
I. 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
Students will be able to use various operators to check the condition and get
appropriate result by performing different operation with the help of supported
operators.
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
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.
Arithmetic Operators: Arithmetic operators are used to perform
mathematicaloperations like addition, subtraction, multiplication, division,
%modulus, exponent etc.
Operato Meaning Descriptio Example Output
r n
+ Addition Adds the value of the left and right >>>1+4 5
operands
- Subtraction Subtracts the value of the right >>>10-5 5
operand
from the value of the left operand
* Multiplication Multiplies the value of the left and >>>5*2 10
right operand
/ Division Divides the value of the left operand >>>10/2 5
by the right operand
** Exponent Performs exponential calculation >>>2**3 8
% Modulus Returns the remainder after dividing >>>15%4 3
the left operand with the right
operand
// Floor Division of operands where >>>17//5 3
Division thesolution is a quotient left
after
removing decimal numbers

Government Polytechnic Mumbai 12


Python Programming (IT19401)

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


LogicalNOT 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) istrue
 For NOT operator- returns TRUE if operand is false
Operato Meaning Description Example Output
r
and Logical If both the operands are true >>>(8>9) and (2<9) False
AND then >>>(9>8)and(2<9) True
condition becomes true.
or Logical OR If any of the two operands are >>>(2==2) or True
non-zero then condition (9<20) Fals
becomestrue. >>>(3!=3) or e
(9>20)
not Logical Used to reverse the logical state >>>not(8>2) False
NOT of its operand. >>>not (2 > 10) True

Bitwise Operators: Bitwise operators acts on bits and performs bit by bit
[Link] a=10 (1010) and b=4 (0100)
Operato Meaning Descriptio Example Output
r n
& Bitwise Operator copies a bit, to the >>>(a&b) 0
AND result,
if it exists in both operands
| Bitwise OR It copies a bit, if it exists in either >>>(a|b) 14
operand.
~ Bitwise It is unary and has the effect of >>>(~a) -11
NOT 'flipping' bits.
^ Bitwise It copies the bit, if it is set in one >>>(a^b) 14
XOR operand but not both.
>> Bitwise The left operand's value is >>>(a>>2) 2
right movedright by the number of
shift bits
specified by the right operand.
<< Bitwise left The left operand's value is moved >>>(a<<2) 40
shift left by the number of bits
specified
by the right operand.
Minimum 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 ifa certain condition is true then a block of statement is executed otherwise
not.
Syntax:
If condition:
Statement(
s)
Example:
i=10
if(i > 20):
Government Polytechnic Mumbai 13
Python Programming (IT19401)

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 thecondition is false.
Syntax:
if (condition):
# if Condition is true, Executes this
blockelse:
# 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
anotherif statement.
Syntax:
if (condition1):
# Executes when condition1 is
trueif (condition2):
# Executes when condition2 is
true# if Block is end here
# if Block is end here
Example:
i =10
if(i ==10):
# First if
statementif(i <
20):
print ("i is smaller than 20")
# Nested - if statement will only be executed if statement above is
trueif (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

Government Polytechnic Mumbai 14


Python Programming (IT19401)

Python if...elif...else Statement


The if...else statement is used to execute a block of code among two alternatives.
However, if we need to make a choice between more than two alternatives, then we
use the if...elif...else statement.
The syntax of the if...elif...else statement is:

f condition1:
# code block 1

elif condition2:
# code block 2

else:
# code block 3

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).This is less like
the for keyword in other programming languages, and works more like an iterator method as found in other object-
orientated programming [Link] the for loop we can execute a set of statements, once for each item in a list, tuple, set
etc.

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

for x in "banana":
print(x)

The break Statement


With the break statement we can stop the loop before it has looped through all the items:

Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.

Print i as long as i is less than 6:

i=1
while i < 6:
print(i)
i += 1

Exit the loop when i is 3:

Government Polytechnic Mumbai 15


Python Programming (IT19401)

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

Practical related Questions


1. Mention the use of //, **, % operator in Python
2. Describe ternary operator in Python
3. Describe about different Logical operators in Python with appropriate examples.
4. Describe about different Arithmetic operators in Python with appropriateexamples.
5. Describe about different Bitwise operators in Python with appropriate examples.
1. Write a program to check whether a number is even or odd
2. Write a program to find out absolute value of an input number
3. Write a program to check the largest number among the three numbers
4. Write a program to check if the input year is a leap year of not
5. Write a program to check if a Number is Positive, Negative or Zero
6. Write a program that takes the marks of 5 subjects and displays the grade.
1. Print the following patterns using loop:
a. *
**
***
****
b. *
***
*****
***
*
c. 1010101
10101
101
1
2. Write a Python program to print all even numbers between 1 to 100 using whileloop.
3. Write a Python program to find the sum of first 10 natural numbers using for loop.
4. Write a Python program to print Fibonacci series.
5. Write a Python program to calculate factorial of a number
6. Write a Python Program to Reverse a Given Number
7. Write a Python program takes in a number and finds the sum of digits in anumber.
8. Write a Python program that takes a number and checks whether it is a

Dated signature
ofTeacher

Government Polytechnic Mumbai 16


Python Programming (IT19401)

Practical No. 3: Develop user defined Python function :

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.

 Python Functions
The fundamentals of Python functions, including what they are, their syntax,their primary
parts, return keywords, and major types, will be covered in thistutorial. Additionally, we’ll
examine several instances of Python function definitions.

 Python Function with parameters


If you have experience in C/C++ or Java then you must be thinking about the return
type of the function and data type of arguments.

 Python Function Arguments


Arguments are the values passed inside the parenthesis of the function. A function can have
any number of arguments separated by a comma.

 Types of Python Function Arguments


Python supports various types of arguments that can be passed at the time of the function call.
In Python, we have the following 4 types of function arguments.

1. Default argument
2. Keyword arguments (named arguments)
3. Positional arguments
4. Arbitrary arguments (variable-length arguments *args and **kwargs)
Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. The following example illustratesDefault arguments.

Keyword Arguments

Government Polytechnic Mumbai 17


Python Programming (IT19401)

The idea is to allow the caller to specify the argument name with values so thatthe caller
does not need to remember the order of parameters.

Positional Arguments
We used the Position argument during the function call so that the first argument(or value) is
assigned to name and the second argument (or value) is assigned to age. By changing the
position, or if you forget the order of the positions, the
values can be used in the wrong places, as shown in the Case-2 example below,where 27 is
assigned to the name and Suraj is assigned to the age

Arbitrary Keyword Arguments


In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variablenumber of
arguments to a function using special symbols. There are two special symbols:
*args in Python (Non-Keyword Arguments)
**kwargs in Python (Keyword Arguments)
Example1:

Government Polytechnic Mumbai 18


Python Programming (IT19401)

Example2:
Def myFun(**kwargs):
For key, value in [Link]():
Print(“%s == %s” % (key, value) myFun(first=’Geeks’,
mid=’for’, last=’Geeks’)

 Python Function within Functions


A function that is defined inside another function is known as the inner function or nested
function. Nested functions are able to access variables of the enclosingscope. Inner functions
are used so that they can be protected from everything happening outside the function.

Government Polytechnic Mumbai 19


Python Programming (IT19401)

 Return multiple values


In Python, you can return multiple values by simply separating them withcommas in the
return statement.
For example, you can define a function that returns a string and an integer as follows:

 Conclusion
Thus from this experiment, we have learned and understand the functionconcept in
python.
Write a Python function that takes a number as a parameter and check the number
isprime or not.
1. Write a Python function to calculate the factorial of a number (a non-
negativeinteger). The function accepts the number as an argument.
2. Write a Python function that accepts a string and calculate the number of
upper caseletters and lower case letters.

Dated signature
ofTeacher

Government Polytechnic Mumbai 20


Python Programming (IT19401)

Practical No. 4: object oriented programming in python


[Link] :- A class is considered as a blueprint of objects. We can think of the
class as a sketch (prototype) of a house. It contains all the details about the
floors, doors, windows, etc. Based on these descriptions we build the house.
House is the object. Since many houses can be made from the same description,
we can create many objects from a class.

Syntax:- class ClassName:#


class definition

Example:- class Bike:


name = ""
gear = 0

In C++ or Java, the constructor has the same name as its class, but it treatsconstructor differently
in Python. It is used to create an object.

Two types of contructor :-

1. prameterized [Link]-

parameterized

Sytanx:- class ClassName:

def init (self): #

Method body

Example:- class PythonGeeks:

def init (self):

print("Object Created for the class PythonGeeks")obj1 =

PythonGeeks()

Government Polytechnic Mumbai 21


Python Programming (IT19401)

4. Self -variable:- The Self parameter is a reference to the current instanceof


the class, and is used to access variables that belongs to the class.

It does not have to be named self , you can call it whatever you like, but ithas
to be the first parameter of any function in the class:

5. Instance variable:- In Python, class variables are bound to a class whileinstance


variables are bound to a specific instance of a class. The instancevariables are also
called instance attributes

6. Class variable:- If the value of a variable is not varied from object to


object, such types of variables are called class variables or static variables.

Class variables are shared by all instances of a class. Unlike instance


variable, the value of a class variable is not varied from object to object,

In Python, Class variables are declared when a class is being [Link] are not defined
inside any methods of a class because of this only one copy of the static variable will be created
and shared between all objects of the class.

7. Private variable:- In actual terms (practically), python doesn’t have anything


called private member variable in Python. However, adding two underlines( ) at the
beginning makes a variable or a method private is theconvention used by most python
code.

 Codes

1. Classes and object:-

# define a class
class Bike:
name = ""
gear = 0

# create object of class


bike1 = Bike()

# access attributes and assign new values


[Link] = 11
[Link] = "Mountain Bike"

print(f"Name: {[Link]}, Gears: {[Link]} ")

Output:-

Government Polytechnic Mumbai 22


Python Programming (IT19401)

Name: Mountain Bike, Gears: 11

2. Constructor:-

class GeekforGeeks:

# default constructor
def init (self):
[Link] = "GeekforGeeks"

# a method for printing data members


def print_Geek(self):
print([Link])

# creating object of the class


obj = GeekforGeeks()

# calling the instance method using the object obj


obj.print_Geek()

Output:-

GeekforGeeks

3. Class Variable:-

class Person:
def init (self, name, age):[Link] =
name
[Link] = age

def str (self):


return f"{[Link]}({[Link]})"p1

= Person("John", 36)

print(p1)

Government Polytechnic Mumbai 23


Python Programming (IT19401)

Output:-
Name=John
Age= 36

[Link] Variable:-
class student:

# constructor
def init (self, name, rollno):

# instance variable
[Link] = name
[Link] = rollno

def display(self):

# using self to access

# variable inside class


print("hello my name is:", [Link])
print("my roll number is:", [Link])

# Driver Code
# object created
s = student('HARRY', 1001)

# function call through object


[Link]()

# accessing variable from


# outside the class
print([Link])

Output:-

hello my name is : harrymy roll

number is:1001 HARRY

Government Polytechnic Mumbai 24


Python Programming (IT19401)

[Link] &private variable:-


class myClass:
privateVar = 27; def
privMeth(self):
print("I'm inside class myClass")def
hello(self):
print("Private Variable value: ",myClass. privateVar)foo =
myClass()
[Link]()
foo. privateMeth

Dated signature
ofTeacher

Government Polytechnic Mumbai 25


Python Programming (IT19401)

Practical No. 5: Write a program in Python to demonstrate following


operations: Simple inheritance, Multiple inheritance

I. Practical Significance
Inheritance allows us to define a class that inherits all the methods and properties
from another class. The existing class is called as Parent class or base class and the
new class which inherited from base class is called Child class or derived class.
 The new class is called derived class or child class & the class from which this
derived class has been inherited is the base class or parent class.
 In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also
provide its specific implementation to the functions of the parent class.

Syntax:
class BaseClass1
#Body of base class
class DerivedClass(BaseClass1):
#body of derived - class
Example:
# Parent class
createdclass Parent:
parentname =
""childname =
""
def show_parent(self):
print([Link])
# Child class created inherits Parent
classclass Child(Parent):
def show_child(self):
print([Link]
e)
ch1 = Child() # Object of Child class
[Link] = "Vijay" # Access Parent class
[Link] = "Parth"
ch1.show_parent() # Access Parent class
methodch1.show_child() # Access Child class
method

a) Multiple inheritance
 Python provides us the flexibility to inherit multiple base classes in the child class.
 Multiple Inheritance means that you're inheriting the property of multiple
classes into one. In case you have two classes, say A and B, and you want to
create a new class which inherits the properties of both A and B.
 So it just like a child inherits characteristics from both mother and father, in
Python, we can inherit multiple classes in a single child class.
Government Polytechnic Mumbai 26
Python Programming (IT19401)

Syntax
:
Syntax:
class A:
# variable of class A
# functions of class
A
class B:
# variable of class A
# functions of class
A
class C(A, B):
# class C inheriting property of both class A and
B# add more properties to class C
Example:
class Add:
def
Addition(self,a,b):
return a+b;
class Mul:
def
Multiplication(self,a,b):
return a*b;
class
Derived(Add,Mul):
def Divide(self,a,b):
return
a/b;d =
Derived()
print([Link](10,20))
print([Link](10,2
0))print([Link](10,20))
Output:
30
200
0.5

Government Polytechnic Mumbai 27


Python Programming (IT19401)

Government Polytechnic Mumbai 28


Python Programming (IT19401)

1. Create a class Employee with data members: name, department and salary.
Createsuitable methods for reading and printing employee information
2. Python program to read and print students information using two classes
usingsimple inheritance.
3. Write a Python program to implement multiple inheritance

Dated signature
ofTeacher

Government Polytechnic Mumbai 29


Python Programming (IT19401)

Practical No. 6: Study of GUI in python .


Canvas ,and different shapes on it.

Tkinter:
Python offers multiple options for developing GUI (Graphical User Interface). Out
of all the GUI methods, tkinter is the most commonly used method. It is a standard
Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the
fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is
an easy task.

Set up Tkinter:
To install the Tkinter module run the below command in the terminal.
 pip install tk
To import the installed module, we import all the methods in the Tkinter library by
using *:
 from tkinter import *

Drawing Shapes in Python Tkinter Canvas:


First, we need to initialize the Tkinter and canvas class. Tkinter Canvas class
contains every method for creating different shapes.

root = Tk()
canvas = Canvas()
[Link]()

1]Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create a main


window, tkinter offers a method ‘Tk(screenName=None, baseName=None, className=’Tk’,
useTk=1)’. To change the name of the window, you can change the className to the desired
one. The basic code used to create the main window of the application is:
root =Tk() where root is the name of the main window object

2]Canvas(): It is used to draw pictures and other complex layout like graphics, text and
widgets.
The general syntax is:
w =Canvas(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.

 bd: to set the border width in pixels.


 bg: to set the normal background color.
 cursor: to set the cursor used in the canvas.
 highlightcolor: to set the color shown in the focus highlight.
 width: to set the width of the widget.
 height: to set the height of the widget.

Government Polytechnic Mumbai 30


Python Programming (IT19401)

3] mainloop(): There is a method known by the name mainloop() is used when your
application is ready to run. mainloop() is an infinite loop used to run the application, wait for
an event to occur and process the event as long as the window is not closed.
[Link]()

After initialization of the Tkinter and canvas class, we start with the drawing of different
shapes.

1) Oval: Oval can be easily drawn using the create_oval() method. This method takes
coordinates, color, outline, width, etc. as a parameter. All shapes are created inside a box
whose coordinates we provide.
canvas.create_oval(x0, y0, x1, y1)

2. Rectangle:By using the create_rectangle() method we draw a rectangle and square shapes.
Here we pass the edges/sides of our shape and hence can draw a square also, using the same
method (all sides equal).
canvas.create_rectangle(x0,y0,x1,y1)

3. Polygon: We can draw as many vertices as we want. We use the create_polygon() method
which takes coordinates of edges and renders them accordingly on our main window. In the
below code we’ve created a list of coordinates and passed it into our create_polygon method.
canvas.create_polygon(x0,y0,x1,y1,…….)

Government Polytechnic Mumbai 31


Python Programming (IT19401)

4. Arc:We can create arc shapes by using create_arc() [Link] like


start,extent,style we can use here
Style will be arc, pieslice,chord by default it is pieslice .
canvas.create_arc(x0,y0,x1,y1)

Common Parameters Used In Create Methods:

Outline :- outline is used to define the color of the shape’s outline.


Fill :- fill is like a paint bucket tool in microsoft paint. It fills the shape with
color we’ve assigned to it.
Width :- used to set the width of the outline.

Program:

Government Polytechnic Mumbai 32


Python Programming (IT19401)

Output:

Conclusion:

From this experiment we can conclude tha we learnt to draw different shapes
using different methods on canvas using tkinter.

Dated signature
ofTeacher

Government Polytechnic Mumbai 33


Python Programming (IT19401)

Practical No 7: To understand Frame widget in Python

 Python Tkinter Frame:-


Python Tkinter Frame widget is used to organize the group of widgets. It acts like a
container which can be used to hold the other widgets. The rectangular areas of the screen
are used to organize the widgets to the python application…

 Syntax :- f = Frame(parent, options) …

 Example
1. from tkinter import *
2. top = Tk()
3. frame = Frame(top)
4. [Link]()
5. [Link]()

Frame Layouts

tkinter also offers access to the geometric configuration of the widgets which can
organize the widgets in the parent windows. There are mainlythree geometry
manager classes class.

1. pack() method:It organizes the widgets in blocks before placing inthe


parent widget.

2. grid() method:It organizes the widgets in grid (table-like structure)


before placing in the parent widget…

3. place() method:It organizes the widgets by placing them on


specific positions directed by the program

Government Polytechnic Mumbai 34


Python Programming (IT19401)

Widgets:-

Widgets in Tkinter are the elements of GUI application which providesvarious


controls (such as Labels, Buttons, ComboBoxes, CheckBoxes, MenuBars, RadioButtons
and many more) to users to interact with the application…

Button:-
To add a button in your application, this widget is used.

Syntax:- b=Button(master, option=value)


master is the parameter used to represent the parent window.
There are number of options which are used to change the format of theButtons.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.

 activebackground: to set the background color when button isunder


the cursor.
 activeforeground: to set the foreground color when button isunder
the cursor.
 bg: to set the normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the button.
 width: to set the width of the button.
 height: to set the height of the button.

Government Polytechnic Mumbai 35


Python Programming (IT19401)

Example:-

from tkinter import*top =


Tk()
[Link]("300x150") frame =
Frame(top) [Link]()
[Link]('Counting Seconds')
button =Button(top, text='Stop', width=25,
command=[Link])
[Link]()
[Link]()

Output :-

Label:
It refers to the display box where you can put any text or image whichcan be updated any
time as per the code.

Syntax:- w=Label(master, option=value)


master is the parameter used to represent the parentwindow.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separatedby commas. Some of them
are listed below…

Government Polytechnic Mumbai 36


Python Programming (IT19401)

Example:-

from tkinter import*

top = Tk() [Link]("300x150")


frame = Frame(top) [Link]()
[Link]('Counting Seconds')
w = Label(frame, text='[Link]!')[Link]()
[Link]()

Output :-

Entry:-

It is used to input the single line text entry from the user.. For multi-line text input, Text
widget is used.

Syntax:- w=Entry(master, option=value)

master is the parameter used to represent the parent window.


There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separatedby commas…

Government Polytechnic Mumbai 37


Python Programming (IT19401)

Example:-

from tkinter import * master = Tk()


[Link]("300x150")

frame =Frame (master) [Link]()


l1=Label(frame, text='First Name')
[Link](row=0)
e1 = Entry(frame) [Link](row=0,
column=1)
l2=Label(frame, text='Last Name')
[Link](row=1)
e2 = Entry(frame)
[Link](row=1, column=1)
mainloop()

Output :-

CheckButton:-

To select any number of options by displaying a number of options to a user

Syntax:- w = CheckButton(master, option=value)


There are number of options which are used to change the format of thiswidget.
Number of options can be passed as parameters separated by commas.

Government Polytechnic Mumbai 38


Python Programming (IT19401)

Example:-

from tkinter import * master = Tk()


[Link]("300x150")frame =
Frame(master) [Link]()
var1 = IntVar()
Checkbutton(frame, text='male', variable=var1).grid(row=0,sticky=W)
var2 = IntVar()
Checkbutton(frame, text='female', variable=var2).grid(row=1,sticky=W)
mainloop()

Output :-

Government Polytechnic Mumbai 39


Python Programming (IT19401)

RadioButton:-

It is used to offer multi-choice option to the user. It offers several options tothe user
and the user has to choose one option.
Syntax:- w = RadioButton(master, option=value)
There are number of options which are used to change the format of thiswidget.
Number of options can be passed as parameters separated by commas.

Example:-

from tkinter import * master = Tk()


[Link]("300x150")frame =
Frame(master) [Link]()
v = IntVar()
Radiobutton(frame, text='GfG', variable=v,
value=1).pack(anchor=W)
Radiobutton(frame, text='MIT', variable=v,
value=2).pack(anchor=W)
mainloop()

Output :-

Government Polytechnic Mumbai 40


Python Programming (IT19401)

Listbox:-

It offers a list to the user from which the user can accept any number ofoptions.

Syntax:- w = Listbox(master, option=value)


master is the parameter used to represent the parent window.
There are number of options which are used to change the format of thewidget.
Number of options can be passed as parameters separated by commas…

Example:-

from tkinter import * master = Tk()


[Link]("300x150")frame =
Frame(master) [Link]()
Lb = Listbox(frame) [Link](1,
'Python')[Link](2, 'Java')
[Link](3, 'C++') [Link](4, 'Any
other')[Link]()
mainloop()

Output :-

SpinBox:-
Government Polytechnic Mumbai 41
Python Programming (IT19401)

It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed


value of numbers.

Syntax:- w = SpinBox(master, option=value)


There are number of options which are used to change the format of thewidget.
Number of options can be passed as parameters separated by commas.

Example:-

from tkinter import * master = Tk()


[Link]("300x150")frame =
Frame(master) [Link]()
w = Spinbox(frame, from_ = 0, to = 10)[Link]()
mainloop()

Output :-

Government Polytechnic Mumbai 42


Python Programming (IT19401)

Scrollbar:-

It refers to the slide controller which will be used to implement listedwidgets.

Syntax:- w = Scrollbar(master, option=value)


master is the parameter used to represent the parent window.
There are number of options which are used to change the format of thewidget.
Number of options can be passed as parameters separated by commas…

Example:-

from tkinter import * master = Tk()


[Link]("300x150")frame =
Frame(master) [Link]()
scrollbar = Scrollbar(frame) [Link]( side = RIGHT, fill
=Y)
mylist = Listbox(frame, yscrollcommand = [Link] )for line in range(100):
[Link](END, 'This is line number' + str(line))[Link]( side = LEFT,
fill = BOTH ) [Link]( command = [Link] )
mainloop()

Output :-

Government Polytechnic Mumbai 43


Python Programming (IT19401)

Bind() method :-
The binding function is used to deal with the events. We can bind Python’s
Functions and methods to an event aswell as we can bind these functions to any
particular widget…

Syntax:- [Link](event, handler)

Command :- The command option associates the button’s action with a


function or a method of a class. When you click or press the button, it’ll
automatically invoke a callbackfunction.

Syntax:- button = [Link](container, text,command)

Example:-

from tkinter import * from


tkinter import ttkwin = Tk()
[Link]("750x250")
F=Frame(win)
[Link]()
def callback():
Label(win, text="Hello World!", font=('Georgia 20bold')).pack(pady=4)
btn = [Link](win, text="Press Enter to Show a Message",command= callback)
[Link](ipadx=10) [Link]('<Return>',lambda
event:callback())[Link]()

Output :-

Government Polytechnic Mumbai 44


Python Programming (IT19401)

Program using all above widget…

Example:-

from tkinter import * base = Tk()


[Link]("500x500")
[Link]("registration form")# Heading
labl_0 = Label(base, text="Registration
form",width=20,font=("bold", 20))
labl_0.place(x=90,y=53)
#Name
lb1= Label(base, text="Enter Name", width=10,font=("arial",12))
[Link](x=20, y=120) en1=
Entry(base) [Link](x=200,
y=120)# Email
lb3= Label(base, text="Enter Email", width=10,font=("arial",12))
[Link](x=19, y=160) en3=
Entry(base) [Link](x=200,
y=160)#contact
lb4= Label(base, text="Contact Number",
width=13,font=("arial",12)) [Link](x=19, y=200)
en4= Entry(base)
[Link](x=200, y=200)#
Gender
lb5= Label(base, text="Select Gender", width=15,font=("arial",12))
[Link](x=5, y=240)vars =
IntVar()
Radiobutton(base, text="Male", padx=5,variable=vars,
value=1).place(x=180, y=240)

Government Polytechnic Mumbai 45


Python Programming (IT19401)

Radiobutton(base, text="Female", padx =10,variable=vars,


value=2).place(x=240,y=240)
#year
lb6= Label(base, text="Year", width=10, font=("arial",12))[Link](x=20, y=270)
var1 = IntVar() Checkbutton(base, text='FY',
variable=var1).place(x=230,y=260)var2 =
IntVar() Checkbutton(base, text='SY',
variable=var2).place(x=230,y=280)#sem
lb5= Label(base, text="SEM", width=13,font=("arial",12))[Link](x=19, y=320)
w = Spinbox(base, from_ = 0, to = 6)[Link](x=200,
y=320)
#PASSWORD
lb6= Label(base, text="Enter Password",
width=13,font=("arial",12)) [Link](x=19, y=350)
en6= Entry(base, show='*')
[Link](x=200, y=350)
# Click Functiondef
click():
name=[Link]()
email=[Link]()
con=[Link]()
y=[Link]()
str="NAME:-- "+name+"\nEMAIL:-"+email+"\nCONTACT:-"+con+"\n"
if y==1:
str=str+"Gender:-male\n"else:
str=str+"Gender:-female\n"

a=[Link]()
b=[Link]() if
a==1:

Government Polytechnic Mumbai 46


Python Programming (IT19401)

str=str+" Year:-FY\n"else:
str=str+"Year :-SY\n"
s=[Link]()
str=str+"SEM:-"+s q=[Link]()
str=str+"\nPassword:-"+q
l=Label(base,text=str)
[Link](x=200,y=500)
#Button
x = Button(base, text="Register",
width=10,bg='brown',fg='white',command =click)
[Link](x=200,y=400)
[Link]()

Output :-

Conclusion:-
Hence from this experiment we have learnt aboutTkinter frame in
python and know how use different types of widget in frame…

Dated signature
ofTeacher

Government Polytechnic Mumbai 47


Python Programming (IT19401)

Practical NO 8:study of file handling with exception handling in python.


1) TYPES OF FILE
1)TEXT
2) BINARY
Opening of file:
f=open(“file name”,”open mode”,”buffering”)
file open mode
1) w – to write data into file. if any data is already present in the file ,it will be deleted and
new data is added. if file does not exist then it will create file.
[Link](str)
2) r-to read data from file. the file pointer is positioned at beginning of file.

3) a –to append the data to the file. file pointer at end. if file does not exit it will create new
file for writing.
4) w+- to write and read the of file. previous data will be deleted.

5) r+ -to read and write data into a file. the previous data will not not deleted. the file pointer
will be at beginning

6)a+ -to append and read the data of file. the file pointer will be at end if file exists. if not
exist then create new file.

closing of file:
A file which is opened should be closed USING close() method.
[Link]()
program 1:

f=open("[Link]","w")
s=input("enter your name:")
[Link](s)
[Link]()

try:
f=open("[Link]","r")
s=[Link]()
print(s)
[Link]()
except:
print("file not found")

try:
f=open("[Link]","a")
s=input("enter name:")
[Link](s)
[Link]()
except:
print("file not found")

Government Polytechnic Mumbai 48


Python Programming (IT19401)

f=open("[Link]","a")
print("enter student names until you enter *")
s=input("name")
while s!='*':
s=input("name")
if(s!='*'):
[Link](s+"\n")
[Link]()

The with statement: the with statement is used while opening the file. the advantage is that
with statement will take care of closing the file which you have open. we need not to close
the file .

with open(“file name”,”mode ”) as fileobject:

with open(“[Link]”,”r”) as f:

The seek() and tell() method:

tell()-it returns the current position o the file pointer.


n=[Link]()

we want to move filepointer to another position we have to user seek()

[Link](offset,fromwhere)

Exercise:
1. develop program to count no of lines in file
2. develop program to copy the content of line from one to another.
3. Develop program to open binary file

Dated signature
ofTeacher

Government Polytechnic Mumbai 49


Python Programming (IT19401)

Practical No 9: study of Regular Expressions(regex) in python

A regular expression is a string that contains special symbols and characters to find or
extract the information needed by us from the given data.
a regular expression helps us to search ,match, find and split the given data as per
requirement.
it is also called as ‘regex’.it is also in other languages like JAVA,Perl

python provide re module that stands for regular [Link] module contains the
methods like

compile(),search(),match(),findall(),split() used to find data from given data.


Methos in RE Module

1)match(): the match() method searches in the beginning of the string .if the matching string
found it returns an object that contains the result otherwise it returns None. we can assess
the string from returned object using group() method.

2)search() : the search() method searches the string from beginning till the end and return
first occurrence of the matching string. otherwise it return None. we use group() method to
retrieve the string from result.

3) findall():the findall() method searches the string from beginning till the endand returns
all occurrences of the matching string in the for of list .if the matching string not found then
it will return empty list. we can use for loop to display result or can directly print list.

4) split()- the split method splits the string according to the regular expression and resultant
pieces are returned as a list. it there are no string pieces then it returns an empty list. we can
print resultant by using for loop.

5) sub(): the sub() method substitutes or replace new strings in place of existing strings
after substitute the main string is returned by this method.
sub(regular expression ,new string, string)

Sequence Characters in Regular Expression:


Characters description
\d -Represents any digit( 0 to 9)
\D -Represents any non digit
\s- Represents a white spaces ex:\t \n \r
\S-Represents non white spaces characters.
\w -Represents any alphanumeric A toZ a to z,0 to 9
\W- Represents any non-alphanumeric
\b- Represents a space around words
\A- Matches only at start of the string
\Z- Matches only at the end of the string
each of this sequence represents a single character in the string

Quantifiers in Regular Expression


Government Polytechnic Mumbai 50
Python Programming (IT19401)

Characters Description

+ - 1 or more repetitions of the preceding regexp


*- 0 or more repetitions of the preceding regexp
? -0 or1 repetitions of the preceding regexp
{m}- Exactly m occurrences
{m,n} -From m to n occurrances . m default 0 and n default infinity

Special characters in Regular Expression Characters Description


\ -Escape special characters nature
.- Matching any character except new line
^- Matches beginning of the string
$- Matches ending of a string
[...] -Denotes the set of possible characters ex:[6b-d] matches any character 6,b,c,or d
A[nkb] n or k or b

[^...] -Matches every character except the one inside [Link][^a-c6] a,b,c or 6

R|S Matches either R or S regex

1) A python program to create a regular expression to retrieve all words starting with a in string

import re
str='an apple a day keeps doctor away'
r=r'a[\w]*'
result=[Link](r,str)
print(result)

2) A python program to create a regular expression to retrieve all words starting with a
numeric digit.
import re
str='the meeting will be at 1st and 2nd day of everymonth'
r=r'\b\d[\w]*\b'
result=[Link](r,str)
for i in result:
print(i)
3) A python program to create a regular expression to retrieve all words
having 5 character length
import re
str='one two three four five six seven eight nine ten'
r=r'\b\w{5}\b'
result=[Link](r,str)
for i in result:
print(i)
4) A python program to create a regular expression to retrieve all the words
having the length of at least 4 characters.
Government Polytechnic Mumbai 51
Python Programming (IT19401)

import re
str='one two three four five six seven eight nine ten'
r=r'\b\w{4,}\b'
result=[Link](r,str)
for i in result:
print(i)
5)A python program to create a regular expression to retrieve all the words
with 3 or 4 or 5 characters.
import re
str='one two three four five six seven eight nine ten be the
part of GPM'
r=r'\b\w{3,5}\b'
result=[Link](r,str)
for i in result:
print(i)
6)A python program to create a regular expression to retrieve only single digit
from a string.
import re
str=' 1 two 3 four 5 six seven 8 9 10'
r=r'\b\d\b'
result=[Link](r,str)
for i in result:
print(i)

7)A python program to create a regular expression to retrieve all words


starting with ‘an’ or ‘ak’
import re
str="anil akhil anant arun arati arundhati abhijeet ankur"
r=r'\ba[nkb][\w]*\b'
res=[Link](r,str)
for i in res:
print(i)
8)A python program to create a regular expression to 5 july 1991

05/07/1991 r’\b\d{2}\\d{2}\\d{4}
05-07-1991
5/7/91 r’\d{1,2}-\d{1,2}-\d{4}
5/7/1991

Government Polytechnic Mumbai 52


Python Programming (IT19401)

import re
f=open("[Link]","r")
str=[Link]()
r=r'\b\d{1,2}-\d{1,2}-\d{2,4}\b'
res=[Link](r,str)
for i in res:
print(i)

Exercise:
1.A python program to create a regular expression to search whether a given string is
starting with ‘He’ or not
2.A python program to create a regular expression to retrieve marks from a given string.
3.A python program to create a regular expression to retrieve email id from given data

Dated signature
ofTeacher

Government Polytechnic Mumbai 53


Python Programming (IT19401)

Practical no:10 Mini project

Students has to apply knowledge of python programming and develop some basic
applications.

Dated signature
ofTeacher

Government Polytechnic Mumbai 54


Python Programming (IT19401)

Government Polytechnic Mumbai 55


Python Programming (IT19401)

Government Polytechnic Mumbai 56

You might also like