PWP Nirali
PWP Nirali
PROGRAMMING WITH
'PYTHON'
(22616)
Semester - VI
THIRD YEAR DIPLOMA IN COMPUTER ENGINEERING GROUP
Price ` 180.00
N4396
PROGRAMMING WITH 'PYTHON' ISBN 978-93-89686-90-6
First Edition : December 2019
© : Author
The text of this publication, or any part thereof, should not be reproduced or transmitted in any form or stored in any computer storage system or device for
distribution including photocopy, recording, taping or information retrieval system or reproduced on any disc, tape, perforated media or other information storage
device etc., without the written permission of Author with whom the rights are reserved. Breach of this condition is liable for legal action.
Every effort has been made to avoid errors or omissions in this publication. In spite of this, errors may have crept in. Any mistake, error or discrepancy so
noted and shall be brought to our notice shall be taken care of in the next edition. It is notified that neither the publisher nor the author or seller shall be
responsible for any damage or loss of action to any one, of any kind, in any manner, therefrom.
DISTRIBUTION CENTRES
PUNE
Nirali Prakashan : 119, Budhwar Peth, Jogeshwari Mandir Lane, Pune 411002, Maharashtra
(For orders within Pune) Tel : (020) 2445 2044, Fax : (020) 2445 1538; Mobile : 9657703145
Email : [email protected]
Nirali Prakashan : S. No. 28/27, Dhayari, Near Asian College Pune 411041
(For orders outside Pune) Tel : (020) 24690204 Fax : (020) 24690316; Mobile : 9657703143
Email : [email protected]
MUMBAI
Nirali Prakashan : 385, S.V.P. Road, Rasdhara Co-op. Hsg. Society Ltd.,
Girgaum, Mumbai 400004, Maharashtra; Mobile : 9320129587
Tel : (022) 2385 6339 / 2386 9976, Fax : (022) 2386 9976
Email : [email protected]
DISTRIBUTION BRANCHES
JALGAON
Nirali Prakashan : 34, V. V. Golani Market, Navi Peth, Jalgaon 425001, Maharashtra,
Tel : (0257) 222 0395, Mob : 94234 91860; Email : [email protected]
KOLHAPUR
Nirali Prakashan : New Mahadvar Road, Kedar Plaza, 1st Floor Opp. IDBI Bank, Kolhapur 416 012
Maharashtra. Mob : 9850046155; Email : [email protected]
NAGPUR
Nirali Prakashan : Above Maratha Mandir, Shop No. 3, First Floor,
Rani Jhanshi Square, Sitabuldi, Nagpur 440012, Maharashtra
Tel : (0712) 254 7129; Email : [email protected]
DELHI
Nirali Prakashan : 4593/15, Basement, Agarwal Lane, Ansari Road, Daryaganj
Near Times of India Building, New Delhi 110002 Mob : 08505972553
Email : [email protected]
BENGALURU
Nirali Prakashan : Maitri Ground Floor, Jaya Apartments, No. 99, 6th Cross, 6th Main,
Malleswaram, Bengaluru 560003, Karnataka; Mob : 9449043034
Email: [email protected]
Other Branches : Hyderabad, Chennai
Note : Every possible effort has been made to avoid errors or omissions in this book. In spite this, errors may have crept in. Any type of error or mistake so noted,
and shall be brought to our notice, shall be taken care of in the next edition. It is notified that neither the publisher, nor the author or book seller shall be responsible
for any damage or loss of action to any one of any kind, in any manner, therefrom. The reader must cross check all the facts and contents with original Government
notification or publications.
[email protected] | www.pragationline.com
• Second chapter focuses on concepts of Python Operators and Control Flow Statements.
A special words of thank to Shri. Dineshbhai Furia, Mr. Jignesh Furia for showing full faith in us
to write this text book. We also thank to Mr. Amar Salunkhe and Mr. Akbar Shaikh of M/s Nirali
Prakashan for their excellent co-operation.
We also thank Ms. Chaitali Takale, Mr. Ravindra Walodare, Mr. Sachin Shinde, Mr. Ashok Bodke,
Mr. Moshin Sayyed and Mr. Nitin Thorat.
Authors
Syllabus ...
1. Introduction and Syntax of Python Program
1.1 Features of Python - Interactive, Object-Oriented, Interpreted, Platform Independent.
1.2 Python Building Blocks - Identifiers, Keywords, Indention, Variables, Comments.
1.3 Python Environment Setup - Installation and Working of IDE.
1.4 Running Simple Python Scripts to Display 'Welcome' Message.
1.5 Python Data Types: Numbers, String, Tuples, Lists, Dictionary, Declaration and Use of Data Types.
2. Python Operators and Control Flow Statements
2.1 Basic Operators: Arithmetic, Comparison/Relational, Assignment, Logical, Bitwise, Membership, Identity
Operators, Python Operator Precedence.
2.2 Control Flow
2.3 Conditional Statements (if, if ... else, nested if)
2.4 Looping in Python (while Loop, for Loop, Nested Loops)
2.5 Loop Manipulation using continue, pass, break, else.
3. Data Structures in Python
3.1 Lists:
(a) Defining Lists, Accessing Values In List, Deleting Values In List, Updating Lists.
(b) Basic List Operations
(c) Built-In List functions
3.2 Tuples:
(a) Accessing Values in Tuples, Deleting Values in Tuples and Updating Tuples.
(b) Basic Tuple Operations.
(c) Built-In Tuple Functions
3.3 Sets:
(a) Accessing Values in Set, Deleting Values in Set and Updating Sets.
(b) Basic Set Operations.
(c) Built-In Set Functions.
3.4 Dictionaries:
(a) Accessing Values in Dictionary, Deleting Values in Dictionary and Updating Dictionary.
(b) Basic Dictionary Operations.
(c) Built-In Dictionaries Functions.
4. Python Functions, Modules and Packages
4.1 Use of Python Built-In Functions (e.g. Type/Data Conversion Functions, Math Functions etc.)
4.2 User Defined Functions: Function Definition, Function Calling, Function Arguments and Parameter
Passing, Return Statement, Scope of Variables: Global Variable and Local Variable.
4.3 Modules: Writing Modules, Importing Modules, Importing Objects from Modules, Python Built-In
Modules (e.g. Numeric and Mathematical Module, Functional Programming Module) Namespace and
Scoping.
4.4 Python Packages: Introduction, Writing Python Packages, Using Standard (e.g. Math, SciPy, NumPy,
Matplotlib, Pandas etc.) and User Defined Packages.
5. Object Oriented Programming in Python
5.1 Creating Classes and Objects.
5.2 Method Overloading and Overriding.
5.3 Data Hiding.
5.4 Data Abstraction.
5.5 Inheritance and Composition Classes.
5.6 Customization via Inheritance Specializing Inherited Methods.
6. File I/O Handling and Exception Handling
6.1 I/O Operations: Reading Keyboard Input, Printing to Screen.
6.2 File Handling: Opening File in different Modes, Accessing File Contents using Standard Library
Functions, Reading and Writing Files, Closing a File, Renaming and Deleting Files, Directories in
Python, File and Directory related Standard Functions.
6.3 Exception Handling: Introduction, Exception Handling - 'try: except:' statement, 'raise' statement.
6.4 User Defined Exceptions.
Contents ...
1. Introduction and Syntax of Python Program 1.1 – 1.30
1.0 Introduction 1.1
1.1 Features of Python 1.2
1.1.1 Running Python Scripts 1.6
1.1.2 Internal Working of Python 1.7
1.2 Python Building Blocks 1.7
1.2.1 Character Set 1.8
1.2.2 Identifiers 1.8
1.2.3 Keywords 1.8
1.2.4 Variables 1.9
1.2.5 Literals 1.10
1.2.6 Indentation 1.12
1.2.7 Commenting in Python 1.13
1.3 Python Environment Setup (Installation and Working of IDE) 1.13
1.4 Running Simple Python Scripts to Display ‘Welcome’ Message 1.20
1.5 Python Data Types 1.21
1.5.1 Numbers Data Type 1.22
1.5.2 String Data Type 1.24
1.5.3 List Data Type 1.26
1.5.4 Tuple Data Type 1.27
1.5.5 Dictionary 1.27
1.6 Input and Output in Python Programming 1.28
• Practice Questions 1.30
Learning Objectives…
[
1.0 INTRODUCTION
• Python is a high-level, interpreted, interactive and object-oriented programming language. Today,
Python is the trendiest programming language programming.
• There are several reasons for why Python programming language is the preferable choice of the
programmers/developers over other popular programming languages like C++, Java and so on.
• Python is popular programming language because of it provides more reliability of code, clean
syntax of code, advanced language features, scalability of code, portability of code, support object
oriented programming, broad standard library, easy to learn and read, support GUI mode,
interactive, versatile and interpreted, interfaces to all major commercial databases, and so on.
History of Python Programming Language:
• Python laid its foundation in the late 1980s. Python was developed by Guido Van Rossum at National
Research Institute for Mathematics and Computer Science in Netherlands in 1990.
• Inspired by Monty Python’s Flying Circus, a BBC comedy series, he named the language Python.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.
• ABC programming language is said to be the predecessor of Python language which was capable of
Exception Handling and interfacing with Amoeba Operating System. Like Perl, Python source code is
now available under the GNU General Public License (GPL).
• In February 1991, Guido Van Rossum published Python 0.9.0 (first release) to alt.sources. In addition
to exception handling, Python included classes, lists and strings.
• In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce which
aligned it heavily in relation to functional programming.
[1.1]
Programming with 'Python' 1.2 Introduction and Syntax of Python Program
• Python 2.0 added new features like list comprehensions, garbage collection system and it supported
Unicode.
• On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify
fundamental flaw of the language. In Python 3.0 the print statement has been replaced with a
print( ) function.
• Python widely used in both industry and academia because of its simple, concise and extensive
support of libraries.
• Python is available for almost all operating systems such as Windows, Mac, Linux/Unix etc. Python
can be downloading from http://www.python.org/downloads.
• Some common applications of Python Programming are listed below:
1. Google's App Engine web development framework uses Python as an application language.
2. Maya, a powerful integrated 3D modeling and animation system, provides a Python scripting
API.
3. Linux Weekly News, published by using a web application written in Python programming.
4. Google makes extensive use of Python in its Web Search Systems.
5. The popular YouTube video sharing service is largely written in Python programming.
6. The NSA (National Security Agency) uses Python programming for cryptography and
intelligence analysis.
7. iRobot uses Python programming to develop commercial and military robotic devices.
8. The Raspberry Pi single-board computer promotes Python programming as its educational
language.
9. Nextflix and Yelp have both documented the role of Python in their software infrastructures.
10. Industrial Light and Magic, Pixar and others uses Python programming in the production of
animated movies.
• In this text book, IDLE is used for Python programming. IDLE (Integrated Development and Learning
Environment) is an Integrated Development Environment (IDE) for Python.
• To start IDLE interactive shell, search for the IDLE icon in the start menu and double click on it and
we will get the following window (See Fig. 1.2).
Programming with 'Python' 1.4 Introduction and Syntax of Python Program
• In Python IDLE shell not only we can execute commands one by one like in Python Command Prompt
but also can create .py files and see execution of those files.
Byte Virtual
Compiler
code machine
Running code
Source code
Library
modules
7. Extensible:
• Python programming implies that other languages such as C/C++ can be used to compile the code
and thus it can be used further in the python code.
• Python has a large and broad library and provides rich set of module and functions for rapid
application development.
• Python languages bulk library is portable and cross platform compatible with Unix, Windows etc.
Limitations of Python:
1. Python is an interpreter based language. Therefore, it is bit slower than compiler based
languages.
2. Python is a high level language like C/C++/Java, it also uses many layers to communicate with
the operating system and the computer hardware.
3. Graphics intensive applications such as games make the program to run slower.
4. Due to the flexibility of the data types, Python's memory consumption is also high.
Structure of a Python Program:
• Fig. 1.4 shows a typical program structure of Python programming.
• Python programming programs are structured as a sequence of statements. A Python statement is
smallest program unit.
• Statements are the instructions that are written in a program to perform a specific task. A Python
statement is a complete instruction executed by the Python interpreter.
• By default, the Python interpreter executes all statements sequentially, but we can change order of
execution using control statements.
#Python Program Structure. Calculate Area and Circumference
Documentation Section
of circle using class. # Documentation section
Import Statement import math # import statement
radius=5 # global declaration Section
Global Declaration Section
class Circle(): # class section
Class Section def getArea(self):
Optional
return math.pi*radius*radius
Data members def getCircumference(self):
return radius*2*math.pi
Members functions def showradius(): # sub Program section
print("Radius =",radius)
Subprogram Section
showradius() # Playground Section
c=Circle()
Essential
Play Ground Section print("Area =",c.getArea()) print("Circumference
=",c.getCircumference())
Output:
Radius = 5
Area = 78.53981633974483
Circumference = 31.41592653589793
Fig. 1.4: Typical Program Structure of Python Programming with Example
• Program structure of Python programming contains following sections:
1. Documentation Section includes the comments that specify the purpose of the program.
A comments that is a non-executable statement which is ignored by the compiler while program
execution. Python comments are written anywhere in the program.
2. Import Section is used includes different built in or user defined modules.
3. Global Declaration Section is used to define the global variables for the programs.
4. Class Section describes the information about the user defined classes in the Python program.
A class is a collection of data members and member functions called method, that operate on
data members.
Programming with 'Python' 1.6 Introduction and Syntax of Python Program
5. Sub Program Section includes use defined functions. The functions include the set of
statements that need to be executed when the function is called form anywhere.
6. Pay Ground Section is the main section of Python program and the main section starts where
the function calling.
1.1.1 Running Python Scripts
• Python has two basic modes namely, normal and interactive.
• The normal script mode is the mode where the scripted and finished .py files are run in the Python
interpreter.
• The interactive mode is a command line shell which gives immediate feedback for each statement,
while running previously fed statements in active memory.
• As new lines are fed into the interpreter, the fed program is evaluated both in part and in whole.
1. Interactive Mode:
• Interactive mode is used for quickly and conveniently running single line or blocks of code. Here’s an
example using the python shell that comes with a basic python installation.
• The “>>>” indicates that the shell is ready to accept interactive commands. For example, if we want
to print the statement “Interactive Mode”, simply type the appropriate code and hit enter.
Fig. 1.5
2. Script Mode:
• In the standard Python shell we can go to “File” → “New File” (or just hit Ctrl + N) to pull up a blank
script to write the code. Then save the script with a “.py” extension.
• We can save it anywhere we want for now, though we may want to make a folder somewhere to store
the code as we test Python out. To run the script, either select “Run” → “Run Module” or press F5.
• We should see something like the following, (See Fig. 1.6 (a) and 1.6 (b)).
1.2.4 Variables
• A variable is like a container that stores values that we can access or change. It is a way of pointing to
a memory location used by a program. We can use variables to instruct the computer to save or
retrieve data to and from this memory location.
• A variable is a name given to a location in the computer's memory location, where the value can be
stored that can be used in the program.
• When we create a variable, some space in the memory is reserved for that variable to store a data
value in it. The size of the memory reserved by the variable depends on the type of data it is going to
hold.
• The variable is so called because its value may vary during the time of execution, but at a given
instance only one value can be stored in it.
Variable Declaration:
• A variable is an identifier, that holds a value. In programming, we say that we assign a value to a
variable. Technically speaking, a variable is a reference to a computer memory, where the value is
stored.
• Basic rules to declare variables in python programming language:
1. Variables in Python can be created from alphanumeric characters and underscore(_) character.
2. A variable cannot begin with a number.
3. The variables are case sensitive. Means Amar is differ the 'AMAR' are two separate variables.
4. Variable names should not be reserved word or keyword.
5. No special characters are used except underscore (_) in variable declaration.
6. Variables can be of unlimited length.
• Python variables do not have to be explicitly declared to reserve memory space. The variable is
declared automatically when the variable is initialized, i.e., when we assign a value to the variable
first time it is declared with the data type of the value assigned to it.
• This means we do not need to declare the variables. This is handled automatically according to the
type of value assigned to the variable. The equal sign (=) i.e., the assignment operator is used to
assign values to variables.
• The operand to the left of the = operator is the name of the variable and the operand to the right of
the = operator is the literal value or any other variable value that is stored in the variable.
Syntax: variable=value
Example: For variable.
>>> a=10
>>> a
10
>>>
• Python language allows assigning a single value to several variables simultaneously.
Example: a=b=c=1
All above three variables are assigned to same memory location, when integer object is created with
value 1.
Programming with 'Python' 1.10 Introduction and Syntax of Python Program
1.2.5 Literals
• A literal refers to the fixed value that directly appears in the program. Literals can be defined as, a
data that is given in a variable or constant.
• Literals are numbers or strings or characters that appear directly in a program. Python support the
following literals:
o String Literals: "hello" , '12345'
o Int Literals: 0, 1, 2, −1, −2
o Long Literals: 89675L
o Float Literals: 3.14
o Complex Literals: 12j
o Boolean Literals: True or False
o Special Literals: None
o Unicode Literals: u"hello"
o List Literals: [], [5, 6, 7]
o Tuple Literals: (), (9), (8, 9, 0)
o Dict Literals: {}, {'x':1}
o Set Literals: {8, 9, 10}
1. String Literals:
• String literals can be formed by enclosing a text in the quotes. We can use both single quote (‘ … ’) as
well as double quotes for (“ … ”) a string.
• In simple words, a string literal is a collection of consecutive characters enclosed within a pair of
single or double quotes.
Example: For string literal.
Fname=‘Hello’
Lname=“Python”
print(Fname)
print(Lname)
Output:
Hello
Python
Programming with 'Python' 1.11 Introduction and Syntax of Python Program
2. Numeric Literals:
• Numeric literals are immutable. Numeric literals comprise number or digits form 0 to 9.
• Numeric literals can belong to following four different numerical types.
int (signed integers) long (long integers) float (floating point) complex (complex)
Numbers (can be both Integers of unlimited Real numbers with both In the form of a+bj
positive (+) and size followed by lower- integer and fractional where a forms the real
negative (−)) with no case or uppercase L. part. part and b forms the
fractional part. Example: 87032845L Example: 26.2 imaginary part of
Example: 100 complex number.
Example: 3.14j
3. Boolean Literals:
• A Boolean literal can have any of the two values namely, True or False.
Example: For Boolean literal.
>>> 5<=2
False
>>> 3<9
True
>>>
4. Special Literals:
• Python contains one special literal i.e., None. It is special constant in Python programming that
represent the absence of a value or null value.
• None is used to specify to that field that is not created. It is also used for end of lists in Python.
Example: For special literal.
>>> val1=10
>>> val2=None # N is in uppercase here
>>> val1
10
>>> val2
>>> print (val2)
None
>>>
5. Literal Collections:
• Collections such as tuples, lists and dictionary are used in Python.
(i) List:
o List contain items of different data types. Lists are mutable i.e., modifiable. The values stored in
list are separated by commas(,) and enclosed within a square brackets ([]). We can store different
type of data in a list.
o Value stored in a list can be retrieved using the slice operator([] and [:]). The plus sign (+) is the
list concatenation and asterisk(*) is the repetition operator.
(ii) Tuple:
o Tuple is used to store the sequence of immutable python objects.
o A tuple can be created by using () brackets and separated by commas (,).
(iii) Directory:
o The directory in Python is a collection of key value pairs created using { }.
o The key and value are separated by a colon (:) and the elements/items are separated by
commas (,).
Programming with 'Python' 1.12 Introduction and Syntax of Python Program
1.2.6 Indentation
• Most of the programming languages like C, C++, Java
use braces { } to define a block of code. Python uses Block 1
indentation. Block 2
• A code block (body of a function, loop etc.) starts with
Block 3
indentation and ends with the first un-indented line.
Block 2, continuation
The amount of indentation is up to us, but it must be
Block 1, continuation
consistent throughout that block.
• Generally, four whitespaces are used for indentation Fig. 1.8: Indentation in Python
and is preferred over tabs, (See Fig. 1.8).
• Indentation helps to convey a better structure of a program to the readers. It is used to clarify the
link between control flow constructs such as conditions or loops, and code contained within and
outside of them.
Programming with 'Python' 1.13 Introduction and Syntax of Python Program
Open the python 3.7.1 version pack and double click on it to start installation.
Fig. 1.11
Fig. 1.12
Programming with 'Python' 1.15 Introduction and Syntax of Python Program
Fig. 1.13
Starting Python in different Modes:
1. Starting Python (Command Line):
• A Python script can be executed at command line also. This can be done by invoking the interpreter
on the application.
• In command line mode, we type the Python programming program on the Python shell and the
interpreter prints the result. The steps are given below:
Step 1 : Press Start button, (See Fig. 1.14).
Fig. 1.14
Programming with 'Python' 1.16 Introduction and Syntax of Python Program
Step 2 : Click on All Programs and then click on Python 3.7 (32 bit) as shown in Fig. 1.14. We will see
Fig. 1.15
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, in Fig. 1.16.
Fig. 1.16
Step 3 : To exit from the command line of Python, use Ctrl+z or quit() followed by Enter.
• When we install Python 3, we also get IDLE (Integrated Development Environment). IDLE includes a
color syntax-highlighting editor, a debugger, the Python Shell, and a complete copy of Python 3’s
Step 1 : Press Start button and click on IDLE (Python 3.7, 32-bit) options.
Programming with 'Python' 1.17 Introduction and Syntax of Python Program
Fig. 1.17
Step 2 : We will see the Python interactive prompt i.e. interactive shell.
Fig. 1.18
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 we
write a command and press enter, the python interpreter will immediately display the
result.
Programming with 'Python' 1.18 Introduction and Syntax of Python Program
Fig. 1.19
Executing Python Programs Scripts:
• In Python IDLEs shell window, click on File, and select the New File or press Ctrl+N.
Fig. 1.20
• As soon as we click on New File, the window appears as shown in Fig. 1.21.
Fig. 1.21
Programming with 'Python' 1.19 Introduction and Syntax of Python Program
Fig. 1.22
• Save the above code with filename. By default, python interpreter will save it using the filename.py.
Here, we save the script with file name test.py.
Fig. 1.23
• To run the Python program, click on Run and then Run Module option or we can press Ctrl+F5.
Fig. 1.24
Programming with 'Python' 1.20 Introduction and Syntax of Python Program
• After clicking Run Module, we will get the output of program on Python shell.
Fig. 1.25
Fig. 1.26
2. 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"Welcome, Python!"
Programming with 'Python' 1.21 Introduction and Syntax of Python Program
• We assume that we have Python interpreter set in PATH variable. Now, try to run this program as
follows:
$ python test.py
Output:
Welcome, Python!
• On Linux OS to execute a Python script modified test.py file:
#!/usr/bin/python
print"Hello, Python!"
• We assume that we 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
Hello, Python!
1.5 PYTHON DATA TYPES
• The type of data value that can be stored in an identifier/variable is known as its data type.
• The data type determines how much memory is allocated to store data and what operations can be
performed on it.
• The data stored in memory can be of many types and are used to define the operations possible on
them and the storage method for each of them.
• Python handles several data types to facilitate the needs of programmers and application developers
for workable data.
Declaration and Use of Data Types:
• One of the main differences between Python and strongly-typed languages like C, C++ or Java is the
way it deals with types. In strongly-typed languages every variable must have a unique data type.
• For example, if a variable is of type integer, solely integers can be saved in the variable. In Java or C,
every variable has to be declared before it can be used. Declaring a variable means binding it to a
data type.
• Declaration of variables is not required in Python. If there is need of a variable, we think of a name
and start using it as a variable.
• In the following line of code, we assign the value 42 to a variable:
i = 42
• The equal "=" sign in the assignment shouldn't be seen as "is equal to". It should be "read" or
interpreted as "is set to", meaning in our example "the variable i is set to 42". Now we will increase
the value of this variable by 1:
>>> i = i + 1
>>> print i
43
>>>
• Python has various standard data types that are used to define the operations possible on them and
the storage method for each of them. Data types in Python programming includes:
1. Numbers: Represents numeric data to perform mathematical operations.
2. String: Represents text characters, special symbols or alphanumeric data.
3. List: Represents sequential data that the programmer wishes to sort, merge etc.
4. Tuple: Represents sequential data with a little difference from list.
5. Dictionary: Represents a collection of data that associate a unique key with each value.
6. Boolean: Represents truth values (true or false).
Programming with 'Python' 1.22 Introduction and Syntax of Python Program
>>> s[1:12:2] # get element from m index to n-1 index with i increments
'el Pto'
>>> s+" Programming" # It will concatenate string
'Hello Python Programming'
>>> type(s)
<class 'str'>
>>> s*3 #It will repeat the string
'Hello PythonHello PythonHello Python'
>>>
Split and Join a String:
• The split() function in Python breaks a string into individual letters. Use split() method to chop up a
string into a list of substrings, around a specified delimiter. The outcome of split() methods gives us
a list.
Example: For split() function.
>>> s="Python programming is easy"
>>> s
'Python programming is easy'
>>> l=s.split() # split() without any argument
>>> l
['Python', 'programming', 'is', 'easy']
>>> s="Python,programming,is,easy"
>>> s
'Python,programming,is,easy'
>>> l=s.split(',') # split() with a argument
>>> l
['Python', 'programming', 'is', 'easy']
>>>
>>> type(l)
<class 'list'>
• Use join() method to join the list back into a string, with a specified delimiter in between. The
outcome of join() method gives us a string.
Example: For join() function/method.
>>> l
['Python', 'programming', 'is', 'easy']
>>>
>>> type(l)
<class 'list'>
>>> s=' '.join(l)
>>> s
'Python programming is easy'
>>> s='.'.join(l)
>>> s
'Python.programming.is.easy'
>>> type(s)
<class 'str'>
Programming with 'Python' 1.26 Introduction and Syntax of Python Program
• Lists are mutable which means that value of elements of a list can be altered by using index.
Example: For list with updation/alteration/modification.
>>> first=[10, 20, 30]
>>> first[2] # print second value in the list
30
>>> first[2]=50 # change second value in the list
>>> first
[10, 20, 50]
>>> first[2] # print second value in the list
50
>>> print (first*2) # prints the list two times
[10, 20, 30, 10, 20, 30]
List and Strings:
• A string is a sequence of characters and list is a sequence of values, but a list of characters is not
same as string. We can convert string to a list of characters.
Example: For conversion of string to a list.
>>> p="Python"
>>> p
'Python'
>>> l=list(p)
>>> l
['P', 'y', 't', 'h', 'o', 'n']
1.5.5 Dictionary
• Dictionary is an unordered collection of key-value pairs. It is the same as the hash table type.
• The order of elements in a dictionary is undefined, but we can iterate over the following:
o The key
o The value
o The items (key-value pairs) in a dictionary.
Programming with 'Python' 1.28 Introduction and Syntax of Python Program
• When we have the large amount of data, the dictionary data type is used. The dictionary data type is
mutable in nature which means we can update modify/update any value in the dictionary.
• Items in dictionaries are enclosed in curly braces { } and separated by the comma (,). A colon (:) is
used to separate key from value. Values can be assigned and accessed using square braces ([]).
Example: For dictionary data type.
>>> dic1={1:"First","Second":2}
>>> dic1
{1: 'First', 'Second': 2}
>>> type(dic1)
<class 'dict'>
>>> dic1[3]="Third"
>>> dic1
{1: 'First', 'Second': 2, 3: 'Third'}
>>> dic1.keys()
dict_keys([1, 'Second', 3])
>>> dic1.values()
dict_values(['First', 2, 'Third'])
>>>
Additional Programs:
1. Program to find the square root of a number.
x=int(input("Enter an integer number:"))
ans=x**0.5
print("Square root= ", ans)
Output:
Enter an integer number: 144
Square root= 12.0
2. Program to find the area of Rectangle.
l=float(input("Enter length of the rectangle: "))
b=float(input("Enter breadth of the rectangle: "))
area=l*b
print("Area of Rectange= ",area)
Output:
Enter length of the rectangle: 5
Enter breadth of the rectangle: 6
Area of Rectange= 30.0
3. Program to calculate area and perimeter of the square.
int(input("Enter side length of square: "))
area=side*side
perimeter = 4*side
print("Area of Square =", area)
print("Perimeter of Square =", perimeter)
Output:
Enter side length of square: 5
Area of Square = 25
Perimeter of Square = 20
4. Program to calculate surface volume and area of a cylinder.
pi=22/7
height = float(input('Height of cylinder: '))
radian = float(input('Radius of cylinder: '))
volume = pi * radian * radian * height
sur_area = ((2*pi*radian) * height) + ((pi*radian**2)*2)
print("Volume is: ", volume)
print("Surface Area is: ", sur_area)
Output:
Height of cylinder: 4
Radius of cylinder: 6
Volume is: 452.57142857142856
Surface Area is: 377.1428571428571
5. Program to swap the value of two variables.
num1=input("Enter first value: ")
num2=input("Enter second value: ")
print("Numbers before swapping")
print("num1= ",num1)
print("num2= ",num2)
temp=num1
num1=num2
Programming with 'Python' 1.30 Introduction and Syntax of Python Program
num2=temp
print("Numbers after swapping")
print("num1= ",num1)
print("num2= ",num2)
Output:
Enter first value: 10
Enter second value: 20
Numbers before swapping
num1= 10
num2= 20
Numbers after swapping
num1= 20
num2= 10
Practice Questions
1. What is Python programming language?
2. Give short history for Python.
3. Enlist applications for Python programming.
4. What are the features of Python?
5. List any four editors used for Python programming.
6. 'Python programming language is interpreted and intractive' comment this sentence.
7. How to run python scripts? Explain in detail.
8. What is interpreter? How it works?
9. Explain the following features of Python programming:
(i) Simple
(ii) Platform independent
(iii) Interactive
(iv) Object Oriented.
10. Explain about the need for learning Python programming and its importance.
11. Describe the internal working of Python diagrammatically.
12. Write in brief about characters set of Python.
13. Write in brief about any five keywords in Python.
14. Write the steps to install Python and to run Python code.
15. What is the role of indentation in Python?
16. How to comment specific line(s) in Python program?
17. What is variable? What are the rules and conventions for declaring a variables?
18. What are the various data types available in Python programming.
19. What are four built-in numeric data types in Python? Explain.
20. What is the difference between interactive mode and script mode of Python.
21. Python has developed as an open source project. Justify this statement.
22. Define the following terms:
(i) Identifier
(ii) Literal
(iii) Data type
(iv) Tuple
(v) List.
23. Explain dictionary data type in detail.
2…
Python Operators and
Control Flow Statements
Chapter Outcomes…
▣ Write simple Python program for the given arithmetic expressions.
▣ Use different types of operators for writing the arithmetic expressions.
▣ Write a 'Python' program using decision making structure for two-way branching to solve the given
problem.
▣ Write a 'Python' program using decision making structure for multi-way branching to solve the given
problem.
Learning Objectives…
[
2.0 INTRODUCTION
• 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. The Python language provides a
rich set of operators.
• The operator and operand when combined to perform a certain operation, it becomes an expression.
For example, in expression x + y, x and y are the variables (operands) and the plus (+) sign is the
operator that specifies the type of operation performed on the variables.
• In any programming language, a program is written as a set of instructions. The instructions written
in programs are termed as statements.
• In Python, statements in a program are executed one after another in the order in which they are
written. This is called sequential execution of the program.
• But in some situations, the programmer may need to alter the normal flow of execution of a
program or to perform the same operations a number of times.
• For this purpose, Python provides a control structure which transfers the control from one part of
the program to some other part of the program.
• A control structure is a statement that determines the control flow of the set of instructions i.e., a
program. Control statements are the set of statements that are responsible to change the flow of
execution of the program.
• There are different types of control statements supported by Python programming like
decision/conditional control, loop/iteration control and jump or loop control.
[2.1]
Programming with 'Python' 2.2 Python Operators and Control Flow Statements
2.1 OPERATORS
• An operator is a symbol which specifies a specific action. An operator is a special symbol that tells
the interpreter to perform a specific operation on the operands. The operands can be literals,
variables or expressions.
• An operand is a data item on which operator acts. Operator
Operators are the symbol, which can manipulate the
value of operands. Some operators require two A + B
operands while others require only one.
• Consider the expression 5 + 2 = 7. Here, 5 and 2 are Operands
called the operands and + is called the operator.
Fig. 2.1: Concept of Operator and Operands
• In Python, the operators can be unary operators or binary operator.
1. Unary Operators:
• Unary operators are operators with only one operand. These operators are basically used to provide
sign to the operand. +, −, ~ are called unary operators.
Syntax: operator operand
Example:
>>> x=10
>>> +x
10
>>> -x
-10
>>> ~x
-11
• The invert (~) operator returns the bitwise inversion of long integer arguments. Inversion of x can be
computed as ~ (x + 1).
2. Binary Operators:
• Binary operators are operators with two operands that are manipulated to get the result. They are
also used to compare numeric values and string values.
Syntax: operand1 operator operand2
• Binary operators are: **, *, /, %, +, -, <<, >>, &, |, ^, <, >, <=, >=, ==, !=, <>.
Example:
>>> x=10
>>> y=20
>>> x+y
>>> -x
30
>>> 2+3
5
Expression:
• An expression is nothing but a combination of operators, variables, constants and function calls that
results in a value.
• In other words, an expression is a combination of literals, variables and operators that Python
evaluates to produce a value.
For examples: 1 + 8
(3 * 9) / 5
a * b + c * 3
• Python operators allow programmers to manipulate data or operands. The types of operators
supported by Python includes Arithmetic operators, Assignment operators, Relational or
Comparison operators, Logical operators, Bitwise operators, Identity operators and Membership
operators.
Programming with 'Python' 2.3 Python Operators and Control Flow Statements
3. NOT Used to reverse the logical state of its Not(a and b) is True.
(Logical NOT Operator) operand.
• Following table shows bitwise operators assume a=10 (1010) and b=4 (0100).
Sr. No. Operator Description Example
1. & This operation performs a&b = 1010 & 0100 = 0000 =0
(Bitwise AND Operator) AND operation between
operands. Operator copies
a bit, to the result, if it
exists in both operands
2. | This operation performs a|b = 1010 | 0100 = 1110 = 14
(Bitwise OR Operator) OR operation between
operands. It copies a bit, if
it exists in either operand.
3. ^ This operation performs a^b=1010 ^ 0100 = 1110 =14
(Bitwise XOR Operator) XOR operations between
operands. It copies the bit,
if it is set in one operand
but not both.
4. It is unary operator and ~a= ~ 1010 = 0101
~
has the effect of 'flipping'
(Bitwise Ones
bits i.e. opposite the bits of
Complement Operator)
operand.
5. << The left operand's value is a<<2 = 1010 << 2 =101000 = 40
(Bitwise Left Shift moved left by the number
Operator) of bits specified by the
right operand.
6. >> The left operand's value is a>>2 = 1010 >> 2 =0010 = 2
(Bitwise Right Shift moved right by the number
Operator) of bits specified by the
right operand.
• Following table shows the outcome of each operations:
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
Example 1:
>>> a=3
>>> b=3.5
>>> print(a is b)
False
>>> a=3
>>> b=4
>>> print(a is b)
False
>>> a=3
>>> b=3
>>> print(a is b)
True
>>>
Example 2:
>>> x=10
>>> print(type(x) is int)
True
>>>
Example 3:
>>> x2 = 'Hello'
>>> y2 = 'Hello'
>>> print(x2 is y2)
True
>>> x3 = [1,2,3]
>>> y3 = [1,2,3]
>>> print(x3 is y3)
False
>>> x4=(1,2,3)
>>> y4=(1,2,3)
>>> print(x4 is y4)
False
• In this example x3 and x4 are equal list but not identical. Interpreter will locate them separately in
memory even though they have equal content. Similarly x4 and y4 are equal tables but not identical.
2.1.7 Membership Operators
• The membership operators in Python programming are used to find the existence of a particular
element in the sequence and used only with sequences like string, tuple, list, dictionary etc.
• Membership operators are used to check an item or an element that is part of a string, a list or a
tuple. A membership operator reduces the effort of searching an element in the list.
• Python provides ‘in’ and ‘not in’ operators which are called membership operators and used to test
whether a value or variable is in a sequence.
Sr. No. Operator Description Example
1. in True if value is found in list or in sequence, >>> x="Hello World"
and false it item is not in list or in sequence >>> print('H' in x)
True
2. not in True if value is not found in list or in >>> x="Hello World"
sequence, and false it item is in list or in >>> print("Hello" not in x)
sequence. False
Programming with 'Python' 2.7 Python Operators and Control Flow Statements
Example:
>>> x="Hello World" # using string
>>> print("H" in x)
True
>>> print("Hello" not in x)
False
>>> y={1:"a",2:"b"} # using dictionary
>>> print(1 in y)
True
>>> print("a" in y)
False
>>> z=("one","two","three") # using tuple
>>> print ("two" in z)
True
• The following table lists all operators from highest precedence to the lowest.
Sr.
Operator Name/Description Assoicativity
No.
1. (), [] Parentheses Left to Right
2. ** Exponent Right to Left
3. +x, −x, ~x Unary plus, Unary minus, Bitwise NOT Right to Left
4. *, /, //, % Multiplication, Division, Floor division, Modulus Left to Right
5. +, − Addition, Subtraction Left to Right
6. <<, >> Bitwise left and right shift operators Left to Right
7. & Bitwise AND Left to Right
8. ^ Bitwise XOR Left to Right
9. | Bitwise OR Left to Right
10. <=, <, >, >= Comparison Operator Left to Right
11. <> == != Equality operators Left to Right
12. = %= /= //= -= Assignment Operators Right to Left
+= *= **=
13. is, is not Identity Left to Right
14. in, not in Membership operators Left to Right
15. NOT, OR, AND Logical Operators NOT, AND, OR Left to Right
• Note that indentation is required for statements which are under if condition.
Control Flow Diagram of if Statement: Example:
i=10
if(i<15):
False
Test Expression print("i is less than 15")
print("This statement is not in if")
True
Output:
Body of if i is less than 15
This statement is not in if
Statement just
below if
Statement just
below if
Test Expression
True Output:
Statement 3
3 i is 20
Body of else
Statement just
below
if-elseif
Output:
Enter first number: 10
Enter second number: 20
Enter third number: 30
largest number is: 30
Body of count=0
loop count=1
count=2
count=3
Next statement
block
Output:
Enter how many number u want to display: 10
Fibonacci Sequence is:
0
1
1
2
3
5
8
13
21
34
Additional Programs:
1. Program to find out the reverse of the given number.
n=int(input('Enter a number: '))
rev=0
while(n>0):
rem=n%10
rev=rev*10+rem
n=int(n/10)
print('Reverse of number=',rev)
Output:
Enter a number: 123
Reverse of number= 321
2. Program to find sum of digit of a given number.
n=int(input('Enter a number:'))
sum=0
while(n>0):
rem=n%10
sum=sum+rem
n=int(n/10)
print('Sum of number=',sum)
Output:
Enter a number: 123
Sum of number= 6
3. Program to check whether the input number is Armstrong.
n=int(input('Enter a number:'))
num=n
sum=0
while(n>0):
rem=n%10
sum=sum+rem*rem*rem
n=int(n/10)
if num==sum:
print(num, "is armstrong")
else:
print(num, "is not armstrong")
Output:
Enter a number: 153
153 is armstrong
Enter a number: 123
123 is not armstrong
Programming with 'Python' 2.14 Python Operators and Control Flow Statements
Next statement
Body
block
of loop
range() Function:
• The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number.
Syntax: range(begin, end, step)
where,
o Start: An integer number specifying at which position to start. Default is 0.
o End: An integer number specifying at which position to end, which is computed as End − 1. This
is mandatory argument to specify.
o Step: An integer number specifying the increment. Default is 1.
Example: For range() function.
>>> list(range(1,6))
[1, 2, 3, 4, 5]
• More examples of range() function:
Example Output
list(range(5)) [0, 1, 2, 3, 4]
list(range(1,5)) [1, 2, 3, 4]
list(range(1,10,2)) [1, 3, 5, 7, 9]
list(range(5,0,-1)) [5, 4, 3, 2, 1]
list(range(10,0,-2)) [10, 8, 6, 4, 2]
list(range(-4,4)) [-4, -3, -2, -1, 0, 1, 2, 3]
list(range(-4,4,2)) [-4, -2, 0, 2]
list(range(0,1)) [0]
list(range(1,1)) [] Empty
list(range(0)) [] Empty
Programming with 'Python' 2.15 Python Operators and Control Flow Statements
Example:
for i in range(1,11):
print (i, end=' ')
Output:
1 2 3 4 5 6 7 8 9 10
• The print() function has end=' ' which appends a space instead of default newline. Hence, the
numbers will appear in one row.
Additional Programs:
1. Program to print prime numbers in between a range.
start=int(input("Enter starting number: "))
end=int(input("Enter ending number: "))
for n in range(start,end + 1):
if (n>1):
for i in range(2,n):
if(n%i)== 0:
break
else:
print(n)
Output:
Enter starting number: 1
Enter ending number: 20
2
3
5
7
11
13
17
19
2. Program to check whether the entered number is prime or not.
n=int(input("Enter a number:"))
for i in range(2,n+1):
if n%i==0:
break
if i==n:
print(n," is prime number")
else:
print(n," is not a prime number")
Output:
Enter a number:5
5 is prime number
Enter a number:4
4 is not a prime number
3. Program to print and sum of all even numbers between 1 to 20.
sum=0
for i in range(0,21,2):
print(i)
sum=sum+i
print("Sum of Even numbers= ",sum)
Programming with 'Python' 2.16 Python Operators and Control Flow Statements
Output:
0
2
4
6
8
10
12
14
16
18
20
Sum of Even numbers= 110
3. Program to find out whether the input number is perfect number or not.
n=int(input("Enter number"))
sum=0
for i in range(1,n):
if n%i==0:
sum=sum+i
if sum==n:
print(n,' is perfect number')
else:
print(n,' is not perfect number')
Output:
Enter number 20
20 is not perfect number
Enter number 28
28 is perfect number
4. Program to generate Student Result. Accept marks of five subject and display result according to
following conditions:
Percentage Division
>=75 First class with Distinction
>=60 and <75 First Class
>=45 and <60 Second Class
>=40 and <45 Pass
<40 Fail
m1=int(input("Enter marks of Subject-1:"))
m2=int(input("Enter marks of Subject-2:"))
m3=int(input("Enter marks of Subject-3:"))
total=m1+m2+m3
per=total/3
print("Total Marks=",total)
print("Percentage=",per)
if per >= 75:
print("Distinction")
elif per >=60 and per<75:
print("First class")
elif per >=45 and per<60:
print("Second class")
elif per >=40 and per<45:
print("Pass")
else:
print("Fail")
Output:
Enter marks of Subject-1:60
Enter marks of Subject-1:70
Enter marks of Subject-1:80
Total Marks= 210
Percentage= 70.0
First class
Programming with 'Python' 2.21 Python Operators and Control Flow Statements
5. Python program to perform Addition Subtraction Multiplication and Division of two numbers.
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
print("Enter which operation would you like to perform?")
ch = input("Enter any of these char for specific operation +,-,*,/: ")
result = 0
if ch == '+':
result = num1 + num2
elifch == '-':
result = num1 - num2
elifch == '*':
result = num1 * num2
elifch == '/':
result = num1 / num2
else:
print("Input character is not recognized!")
print(num1, ch , num2, ":", result)
Output:
Enter First Number: 20
Enter Second Number: 10
Enter which operation would you like to perform?
Enter any of these char for specific operation +,-,*,/: *
20 * 10 : 200
6. Program to check whether a string is a palindrome or not.
string=input("Enter string:")
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("The string isn't a palindrome")
Output:
Enter string: abc
The string isn't a palindrome
Enter string: madam
The string is a palindrome
7. Program to check whether a number is a palindrome or not.
num = int(input("enter a number: "))
temp = num
rev = 0
while temp != 0:
rev = (rev * 10) + (temp % 10)
temp = temp // 10
if num == rev:
print("number is palindrome")
else:
print("number is not palindrome")
Programming with 'Python' 2.22 Python Operators and Control Flow Statements
Output:
enter a number: 121
number is palindrome
enter a number: 123
number is not palindrome
8. Program to return prime numbers from a list.
list=[3,2,9,10,43,7,20,23]
print("list=",list)
l=[]
print("Prime numbers from the list are:")
for ain list:
prime=True
for i in range(2,a):
if (a%i==0):
prime=False
break
if prime:
l.append(a)
print(l)
Output:
list= [3, 2, 9, 10, 43, 7, 20, 23]
Prime numbers from the list are:
[3, 2, 43, 7, 23]
9. Program to add, subtract, multiply and division of two complex numbers.
print("Addition of two complex numbers : ",(4+3j)+(3-7j))
print("Subtraction of two complex numbers : ",(4+3j)-(3-7j))
print("Multiplication of two complex numbers : ",(4+3j)*(3-7j))
print("Division of two complex numbers : ",(4+3j)/(3-7j))
Output:
Addition of two complex numbers : (7-4j)
Subtraction of two complex numbers : (1+10j)
Multiplication of two complex numbers : (33-19j)
Division of two complex numbers : (-0.15517241379310348+0.6379310344827587j)
10. Program to find the best of two test average marks out of three test’s marks accepted from the
user.
n1=int(input('enter a number'))
n2=int(input('enter 2nd number'))
n3=int(input('enter the 3rd number'))
avg1=(n1+n2)/2
avg2=(n2+n3)/2
avg3=(n3+n1)/2
maxm=max(avg1, avg2, avg3)
print(maxm)
Programming with 'Python' 2.23 Python Operators and Control Flow Statements
Practice Questions
1. What is operator? Which operators used in Python?
2. What is meant by control flow of a program?
3. Define the terms: (i) Loop, (ii) Program, (iii) Operator, (iv) Control flow.
4. What are the different loops available in Python?
5. What happens if a semicolon (;) is placed at the end of a Python statement?
6. Explain about different logical operators in Python with appropriate examples.
7. Explain about different relational operators in Python with examples.
8. Explain about membership operators in Python.
9. Explain about Identity operators in Python with appropriate examples.
10. Explain about arithmetic operators in Python.
11. List different conditional statements in Python.
12. What are the different nested loops available in Python?
13. What are the different loop control (manipulation) statements available in Python? Explain with
suitable examples.
14. Explain if-else statement with an example.
15. Explain continue statement with an example.
16. Explain use of break statement in a loop with example.
17. Predict output and justify your answer: (i)−11%9 (ii) 7.7//7 (iii) (200-70)*10/5 (iv) 5*1**2.
Programming with 'Python' 2.24 Python Operators and Control Flow Statements
Learning Objectives…
[
3.0 INTRODUCTION
• A data structure is a specialized format for organizing and storing data, so that various operations
can be performed on it efficiently and easily.
• Any data structure is designed to organize data to suit a specific purpose so that it can be accessed
and worked with in appropriate and systematic manner/way. There are four data structures in
Python namely, list, tuple, dictionary and set.
• A data structure that stores an ordered collection of items in Python is called a list. In other words, a
list holds a sequence of items or elements.
• Similar to a list, the tuple is an ordered sequence of items. A set is an unordered collection of unique
items in Python. A dictionary in Python is an unordered collection of key value pairs.
• The data types that are most used in Python are strings, tuples, lists and dictionaries. These are
collectively called as data structures.
3.1 LISTS
• A list in Python is a linear data structure. The elements in the list are stored in a linear order one
after other. 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. The index in lists always
starts with 0 and ends with n-1, if the list contains n elements.
[3.1]
Programming with 'Python' 3.2 Data Structures in Python
Defining List:
• 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.
• Syntax for defining a list in Python is: <list_name> = [value1, value2, … valueN]
Here, list_name is the name of the list and value1, value2, …. valueN are list of values assigned to the
list.
Example: Emp = [20, “Amar”, ‘M’, 50]
• Lists are mutable or changeable. The value of any element inside the list can be changed at any point
of time. Each element or value that is inside of a list is called an item.
• A list data type is a flexible data type that can be modified according to the requirements, which
makes it a mutable data type. It is also a dynamic data type. Lists can contain any sort of object. It can
be numbers, strings, tuples and even other lists.
3.1.1 Creating a List
• We can create a list by placing a comma separated sequence of values in square brackets [].
• The simplest method to create a list by simply assigning a set of values to the list using the
assignment operator (=).
Example: Creating an empty list.
>>> l1=[] # Empty list
>>> l1 # display l1
[]
>>> l1=list() # Using list() constructor
>>> l1
[]
Example: Creating a list with any integer elements.
>>> l2=[10,20,30] # List of Integers
>>> l2
[10, 20, 30]
>>> l2=list([10,20,30])
>>> l2
[10, 20, 30]
Example: Creating a list with string elements.
>>> l3=["Mango","Orange","Banana"] # List of Strings
>>> l3
['Mango', 'Orange', 'Banana']
>>> l3=list(["red","yellow","green"] )
>>> l3
['red', 'yellow', 'green']
Example: Creating a list with mixed data.
>>> l4=[1,"Two",11.22,'X'] # List of mixed data types
>>> l4
[1, 'Two', 11.22, 'X']
• We can convert other data types to lists using Python’s list() constructor.
Example: Create a list using inbuilt range() function.
>>> l5=list(range(0,5))
>>> l5
[0, 1, 2, 3, 4]
Programming with 'Python' 3.3 Data Structures in Python
• Following table shows the list methods used for updating list.
Sr.
Method Syntax Argument Description Return Type
No.
1. append() list.append(item) The item can be numbers, Only modifies the
strings, another list, original list. It does not
dictionary etc. return any value.
2. extend() list1.extend(list2) This extend() method Only modifies the
takes a list and adds it to original list. It doesn't
the end. return any value.
3. insert() list.insert(index, element) This index is position It does not return
where an element needs anything; returns
to be inserted element - None.
this the element to be
inserted in the list.
• Let use see above methods in detail:
1. append() Method: The append() method adds an element to the end of a list. We can insert a
single item in the list data time with the append().
Example: For append() method.
>>> list1=[10,20,30]
>>> list1
[10, 20, 30]
>>> list1.append(40) # add element at the end of list
>>> list1
[10, 20, 30, 40]
2. extend() Method: The extend() method extends a list by appending items. We can add several
items using extend() method.
Example: Program for extend() method.
>>> list1=[10, 20, 30, 40]
>>> list1
[10, 20, 30, 40]
>>> list1.extend([60,70]) # add elements at the end of list
>>> list1
[10, 20, 30, 40, 60, 70]
3. insert() Method: We can insert one single item at a desired location by using the method insert()
or insert multiple items by squeezing it into an empty slice of a list.
Example: Program for insert() method.
>>> list1=[10, 20]
>>> list1
[10,20]
>>> list1.insert(1,30)
>>> list1
[10, 30, 20]
>>> list1=insert(1,[15,25])
>>> list1
[10,[15, 25], 30, 20]
Programming with 'Python' 3.6 Data Structures in Python
th
>>> list1[:4] # list[:n] will return elements indexed from first index to n-1 index
[10, 20, 30, 40]
>>> list1[1:3] # list[m:n] will return elements indexed from m to n-1.
[20, 30]
>>> list1[5]
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
list1[5]
IndexError: list index out of range
2. Negative Indexing: Python allows negative indexing for its sequences. The index of −1 refers to
the last item, −2 to the second last item and so on.
list2 = p y t h o n
-6 -5 -4 -3 -2 -1
Fig. 3.2: List with Negative Index
Example: For negative indexing in list.
>>> list2=['p','y','t','h','o','n']
>>> list2[-1]
'n'
>>> list2[-6]
'p'
>>> list2[-3:]
['h', 'o', 'n']
>>> list2[-7]
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
list2[-7]
IndexError: list index out of range
3.2 TUPLES
• A tuple is also a linear data structure. A Python tuple is a sequence of data values called as items or
elements. A tuple is a collection of items which is ordered and unchangeable.
• A tuple is a data structure that is an immutable or unchangeable, ordered sequence of
elements/items. Because tuples are immutable, their values cannot be modified.
• A tuple is a heterogeneous data structure and used for grouping data. Each element or value that is
inside of a tuple is called an item.
• A tuple is an immutable data type. An immutable data type means that we cannot add or remove
items from the tuple data structure.
• In Python tuples are written with round brackets ( ) and values in tuples can also be accessed by their
index values, which are integers starting from 0.
• Tuples are the sequence or series values of different types separated by commas (,). Tuples are just
like lists, but you can not change their values.
Difference between Tuples and Lists:
1. A values in the list can be replaced with another any time after its creation, whereas in tuples,
the values in it cannot be replaced with another, once tuples are created.
2. Lists allows us to add new items to it, but tuple does not allow us to add new items, once it is
created.
3. We generally use tuple for heterogeneous (different) datatypes and list for homogeneous
(similar) data types.
Programming with 'Python' 3.11 Data Structures in Python
4. Since, tuple are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
5. Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not
possible.
6. Tuples can be used as values in sets whereas lists can not.
7. Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values
like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists
are not immutable.
• Following table shows difference between strings, tuples and lists.
Immutable (Value cannot be modified) Mutable (values can be modified)
Sr.
Strings Tuples List
No.
str="hi" tuples=(5,4.0,'a') list=[5,4.0','a']
1. Sequence Unicode Ordered sequence. Order sequence.
character.
2. Values cannot be modified. Same as list but it is faster Value can be changed dynamically.
than list because it is
immutable.
3. It is a sequence of Values stored in alpha Values stored in alpha numeric.
character. numeric.
4. Access values from string. Access values from tuples. Access values from list.
5. Adding values in not Adding values is not Adding values is possible.
possible. possible.
6. Removing values is not Removing values is not Removing values is possible.
possible. possible.
2. Membership Function:
• We can test if an item exists in a tuple or not, using the keyword in. The in operator evaluates to true
if it finds a variable in the specified sequence and false otherwise.
Example: For membership function in tuple.
>>> tuple
(10, 20, 30, 40, 50)
>>> 30 in tuple
True
>>> 25 in tuple
False
3. Iterating through a Tuple:
• Iteration over a tuple specifies the way which the loop can be applied to the tuple.
• Using a for loop we can iterate through each item in a tuple. Following example uses a for loop to
simply iterates over a tuple.
Example: For iterating items in tuple using for loop.
>>> tuple=(10,20,30)
>>> for i in tuple:
print(i) # use two enter to get the output
Output:
10
20
30
>>>
Methods of Tuple:
Sr. No. Function Description Example
1. count() Returns the number of times a >>> tup1
specified value occurs in a tuple (1, 2, 3, 2, 4)
>>> tup1.count(2)
2
2. index() Searches the tuple for a >>> tup1
specified value and returns the (1, 2, 3)
position of where it was found >>> tup1.index(3)
2
3.3 SETS
• The set data structure in Python programming is implemented to support mathematical set
operations. Set is an unordered collection of unique items. Items stored in a set are not kept in any
particular order.
• A set data structure in python programming includes an unordered collection of items without
duplicates. Sets are unindexed that means we cannot access set items by referring to an index.
• Sets are changeable (mutable) i.e., we can change or update a set as and when required. Type of
elements in a set need not be the same, various mixed data type values can also be passed to the set.
• The sets in python are typically used for mathematical operations like union, intersection,
difference and complement etc.
3.3.1 Accessing Values in Sets
• A set is used to contain an unordered collection of items. There are two ways for creation of sets in
python:
1. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered.
Syntax for defining set in Python is: <set_name>={value1, value2,….,valueN}
Example: Emp={20, "Amar", 'M', 50}
Example: For creating sets with { }.
>>> a={1,3,5,4,2}
>>> print("a=",a)
a = {1, 2, 3, 4, 5}
>>> print(type(a))
<class 'set'>
>>> colors = {'red', 'green', 'blue,’red’'}
>>> colors
{'blue', 'red', 'green'}
>>>
A set does not contain any duplicate values or elements. We can perform set operations like union,
intersection on two sets. Set have unique values. They eliminate duplicates.
Example:
>>> a={1,2,2,3,3,3}
>>> a
{1, 2, 3}
>>>
Programming with 'Python' 3.17 Data Structures in Python
>>> a={2,4,6,8}
>>> a.add(3)
>>> print(a)
{2, 3, 4, 6, 8}
>>>
2. Using update() Method:
• The update() adds elements from lists/strings/tuples/sets to the set.
• The update() method can accepts lists, strings, tuples as well as other sets as its arguments. In all of
these cases, duplicate elements are avoided.
Syntax: A.update(B)
Here, B can be lists/strings/tuples/sets and A is set which will be updated without duplicate entries.
Example: For update() method which updates sets.
>>> a={1,2,3}
>>> b={'a','b','c'}
>>> a
{1, 2, 3}
>>> b
{'c', 'b', 'a'}
>>> a.update(b)
>>> a
{1, 2, 3, 'b', 'a', 'c'}
>>> a.update({3,4})
>>> a
{1, 2, 3, 'b', 4, 'a', 'c'}
>>> C=A - B
>>> C
Fig. 3.5: Difference Operation
{8, 6}
4. Symmetric Difference:
• Symmetric Difference operation performed by using ^ operation. The symmetric difference of
Two Sets A and B is the set (A − B) ∪ (B − A). It represent set of all elements which belongs either to
A or B but not both.
Example: For symmetric difference operation in sets.
>>> A={1,2,4,6,8}
>>> B={1,2,3,4,5} A B
>>> C=A ^ B
>>> C
Fig. 3.6: Symmetric Difference Operation
{3, 5, 6, 8}
3.4 DICTIONARIES
• The dictionary data structure is used to store key value pairs indexed by keys. A dictionary is an
associative data structure, means that elements/items are stored in a non linear fashion.
• Python dictionary is an unordered collection of items or elements. Items stored in a dictionary are
not kept in any particular order. The Python dictionary is a sequence of data values called as items or
elements.
• While other compound data types have only value as an element, a dictionary has a key:value pair.
Each value is associated with a key.
• Dictionaries are optimized to retrieve values when the key is known. A key and its value are
separated by a colon (:) between them.
• The items or elements in a dictionary are separated by commas and all the elements must be
enclosed in curly braces.
Syntax for define a dictionary in Python programming is as follows:
<dictionary_name> = {key1:value1, key2:value2, …keyN:valueN}
Example: Emp = {“ID”:20, “Name”:“Amar”, “Gender”:Male, “SalaryPerHr”:50}
Programming with 'Python' 3.22 Data Structures in Python
• A pair of curly braces with no values in between is known as an empty dictionary. Dictionary items
are accessed by keys, not by their position (index).
• The values in a dictionary can be duplicated, but the keys in the dictionary are unique. Dictionaries
are changeable (mutable). We can change or update the items in dictionary as and when required.
• The key can be looked up in much the same way that we can look up a word in a paper-based
dictionary to access its definition i.e., the word is the ' key' and the definition is its corresponding
'value'.
• Dictionaries can be nested i.e. a dictionary can contain another dictionary.
3.4.1 Creating Dictionary
• A dictionary can be used to store a collection of data values in a way that allows them to be
individually referenced. However, rather than using an index to identify a data value, each item in a
dictionary is stored as a key value pair.
• The simplest method to create dictionary is to simply assign the pair of key:values to the dictionary
using operator (=).
• There are two ways for creation of dictionary in python.
1. We can create a dictionary by placing a comma-separated list of key:value pairs in curly braces
{}. Each key is separated from its associated value by a colon(:).
Example: For creating a dictionary using { }.
>>> dict1={} # Empty dictionary
>>> dict1
{}
>>> dict2={1:"Orange", 2:"Mango", 3:"Banana"} # Dictionary with integer keys
>>> dict2
{1: 'Orange', 2: 'Mango', 3: 'Banana'}
>>> dict3={"name":"vijay", 1:[10,20]} # Dictionary with mixed keys
>>> dict3
{'name': 'vijay', 1: [10, 20]}
2. Python provides a build-in function dict() for creating a dictionary.
Example: Creating directory using dict().
>>> d1=dict({1:"Orange",2:"Mango",3:"Banana"})
>>> d2=dict([(1,"Red"),(2,"Yellow"),(3,"Green")])
>>> d3=dict(one=1, two=2, three=3)
>>> d1
{1: 'Orange', 2: 'Mango', 3: 'Banana'}
>>> d2
{1: 'Red', 2: 'Yellow', 3: 'Green'}
>>> d3
{'one': 1, 'two': 2, 'three': 3}
2. Using get() method returns the value for key if key is in the dictionary, else None, so that this
method never raises a KeyError.
Example: For accessing dictionary elements by get().
>>> dict1={'name':'vijay','age':40}
>>> dict1.get('name')
'vijay'
>>> dict1.get('adr')
2. Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys
but something like [‘key’] is not allowed.
Example:
>>> dict={[1]:'Vijay',2:'Amar',3:'Santosh'}
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
dict={[1]:'Vijay',2:'Amar',3:'Santosh'}
TypeError: unhashable type: 'list'
• Single and double quoted strings are same and we can use a single quote within a string when it is
surrounded by double quote and vice versa.
Example: For string.
>>> a='Hello Python'
>>> a
'Hello Python'
>>> a="Hello Python"
>>> a
'Hello Python'
>>> type(a)
<class 'str'>
str Class:
• Strings are objects of the str class. We can create a string using the constructor of str class
S1=str() # creates an empty string object
S2=str(“Hello”) # creates a string object for Hello
• An alternative wat to create a string object is by assigning a string value to a variable.
Example: For str class.
S1=”” # create an empty string
S2=”Hello” # equivalent to S2=str(“Hello”)
str() Function:
• The str function is used to convert a number into a string.
Example: For str().
>>> a=10
>>> type(a)
<class 'int'>
>>>str(a) # converting int number to string
'10'
Python Built-in Functions for String:
Sr. No. Function Example
1. len() function return the number of characters in a string. >>> a="PYTHON"
>>> len(a)
6
2. min() function return the smallest character in a string. >>> a="PYTHON"
>>> min(a)
'H'
3. max() function return the largest character in a string. >>> a="PYTHON"
>>> max(a)
'Y'
Deleting Entire String:
• Deletion of entire string is possible with the use of del keyword.
Example: For deletion of string.
>>> a="PYTHON"
>>> a
'PYTHON'
>>> del a
Programming with 'Python' 3.28 Data Structures in Python
>>> a
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
a
NameError: name 'a' is not defined
+ operator (String Concatenation):
• The concatenation operator (+) is used to join two strings.
Example: For + operator in string.
>>> "Hello" + "Python"
'HelloPython'
>>> s1="Hello"
>>> s2="Python"
>>> s1+s2
'HelloPython'
* Operator (String Multiplication):
• The multiplication (*) operator is used to concatenate the same string multiple times, it is called
repetition operator.
Example: for * operator in string.
>>> s1="Hello "
>>> s2=3*s1
>>> s2
'Hello Hello Hello '
>>> "**"*5
'**********'
>>> a="**"
>>> a*5
'**********'
>>>
String Traversal (Traversing String with for Loop and while Loop):
• Traversal is a process in which we access all the elements of the string one by one using for and while
loop.
Example: Traversing using for loop.
>>> s=”Python Programming”
>>> for ch in s:
print(ch,end="")
Python Programming
>>> for ch in range(0,len(s),2):
print(s[ch],end="")
Immutable Strings:
• Strings are immutable which means that we cannot change any element of a string. If we want to
change an element of a string, we have to create a new string.
Example: For immutable string.
>>>str="Python"
>>>str
'Python'
>>>str[0]="H"
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
str[0]="H"
TypeError: 'str' object does not support item assignment
th
• Here, when we try to change the 0 index of string to a character “H”, but the python interpreter
generates an error. The solution to this problem is to generate a new string rather than change the
old string.
Example:
>>>str="Python"
>>> str1='H'+str[1:]
>>> str1
'Hython'
• Consider the following two similar strings:
Str1=”Python”
Str2=”Python”
Here, Str1 and Str2 have the same content. Thus python uses one object for each string which has the
same content. Both Str1 and St2 refers to the same string object, whereas Str1 and Str2 have the
same ID number.
Example:
>>> Str1="Python"
>>> Str2="Python" Str1
Str
>>> id(Str1)
Str2 Str object for "Python"
54058464
>>> id(Str2) Fig. 3.7
54058464
String Indices and Accessing String Elements:
• Strings are arrays of characters and elements of an array can be accessed using indexing. Indices
start with 0 from left side and −1 when starting from right side.
S1=“Hello Python”
Character H e l l o P y t h o n
Index (From Left) 0 1 2 3 4 5 6 7 8 9 10 11
Index (From Right) –12 –11 –10 –9 –8 –7 –6 –5 –4 –3 –2 –1
Example:
>>> s1="Hello Python"
>>> print(s1[0]) # print first character
H
>>> print(s1[11]) # print last character
n
>>> print(s1[-12]) # print first character
Programming with 'Python' 3.30 Data Structures in Python
H
>>> print(s1[-1]) # print last character
n
>>> print(s1[15]) # out of index range
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
print(s1[15])
IndexError: string index out of range
>>>
'in' and ‘not in’ Operator in Strings:
• The 'in' operator is used to check whether a character or a substring is present in a string or not. The
expression returns a Boolean value.
Example: For in and out operators.
>>> s1="Hello Python"
>>> "Hello" in s1
True
>>> "java" in s1
False
>>> "Hello" not in s1
False
>>> 'H' in s1
True
>>> 'B' in s1
False
>>> 'Py' in s1
True
>>>
String Slicing:
• A piece or subset of a string is known as slice. To cut a substring from a string is called string slicing.
• Slice operator is applied to a string with the use of square braces([]). Operator [min] will give a
substring which consists of letters between m and n indices, including letter at index m but
th th
excluding that at n, i.e. letter from m index to (n-1) index.
rd th th
• Here two indices are used separated by a colon (:). A slice 3:7 means indices characters of 3 , 4 , 5
th
and 6 positions. The second integer index i.e. 7 is not included. You can use negative indices for
slicing.
Syntax:
stringname[start_index:end_index]
stringname[start_index:end_index:step_size]
Example:
>>> s1=”Hello Python”
>>> s1[0:4]
'Hell'
>>> s1[:2]
'He'
>>> s1[2:]
'llo Python'
Programming with 'Python' 3.31 Data Structures in Python
>>> s1[0:len(s1):2]
'HloPto'
>>> s1[-1:0:-1]
'nohtyPolle'
>>> s1[:-1]
'Hello Pytho'
String Comparison:
• Operators such as ==, <, >, <=, >= and != are used to compare the strings.
Example: For string competition.
>>> S1="abcd"
>>> s2="abcd"
>>> s1>s2
True
• Note: Python compares the numeric value of each character. The ASCII value of ‘a’ is 97 and ASCII
numeric value of ‘A’ is 65. It means 97>65, thus it returns True. However, character by character
comparison goes on till the end of the string.
>>> s1="abcd"
>>> s2="abcd"
>>> s1==s2
True
>>>s1="abcd"
>>> s2="defg"
>>> s1>s2
False
Special Characters in String:
• The backslash (\) character is used to introduce a special character or escape character. It converts
difficult-to-type characters into a string.
Escape
Sr. No. Meaning Example
Character
1. \ newline Ignored >>> print("line1\line2\line3")
line1line2line3
2. \\ Backslash (\) >>> print("This is a backslash (\\) mark")
This is a backslash (\) mark
3. \’ Single Quote (‘) >>> print("These are \'single quote\'")
These are 'single quote'
4. \” Double Quote (“) >>> print("These are \"double quote\"")
These are "double quote"
5. \a ASCII Bell (BELL) >>> print("\a")
6. \b ASCII Backspace (BS) >>> print("Hello \b World!")
Hello World!
7. \f ASCII Formfeed (FF) >>> print("Hello \f World!")
Hello World!
8. \n ASCII Linefeed (LF), Newline >>> print("This is a first line \n This is
a second line")
This is a first line
This is a second line
contd. …
Programming with 'Python' 3.32 Data Structures in Python
3. count(str, beg, Counts the number of times str >>> s1="python programming"
end) occurs in the string or in a >>> s1.count('o')
substring provided that starting 2
index is beg and ending index is >>> s1.count('o',5,18)
end. 1
4. decode() Decodes the string using the >>> s1
codec registered for encoding. 'python Programming'
>>> s1=s1.encode()
>>> s1
b'python Programming'
>>> s1=s1.decode()
>>> s1
'python Programming'
5. encode() Returns encoded string version s1="python Programming"
of string; on error, default is to >>> s1.encode()
raise a ValueError unless errors b'python Programming'
is given with 'ignore' or 'replace'.
6. endswith(suf ix, Determines if string or a >>> s1="python programming is
beg, end) substring of string (if starting easy to learn."
index beg and ending index end >>> s1.endswith('learn')
are given) ends with suffix; False
returns true if so and false >>> s1.endswith('learn.')
otherwise. True
>>> s1.endswith('is',7,26)
False
>>> s1.endswith('easy',7,26)
True
7. expandstab It returns a copy of the string in >>> s1="python\tprogramming"
(tabsize) which tab characters ie. '\t' are >>> s1
expanded using spaces, 'python\tprogramming'
optionally using the given >>> s1.expandtabs()
tabsize (default 8). 'python programming'
>>> s1.expandtabs(16)
'python programming'
8. enumerate() The enumerate() method adds >>>
counter to an iterable and s1=['Orange','Mango','Banana','Pi
returns it (the enumerate object). neapple']
>>> s2=enumerate(s1)
>>> print(list(s2))
[(0, 'Orange'), (1, 'Mango'),
(2, 'Banana'), (3, 'Pineapple')]
9. find(str, beg, Determine if str occurs in string >>> s1="python programming"
end) or in a substring of string if >>> s1.find("prog")
starting index beg and ending 7
index end are given returns >>> s1.find("prog",5)
index if found and -1 otherwise. 7
>>> s1.find("prog",10)
-1
contd. …
Programming with 'Python' 3.34 Data Structures in Python
10. index(str, beg, Same as find(), but raises an >>> s1="python programming"
end) exception if str not found. >>> s1.index("prog")
7
>>> s1.index("prog",10)
Traceback (most recent call last):
File "<pyshell#64>", line 1, in
<module>
s1.index("prog",10)
ValueError: substring not found
11. isalnum() Returns true if string has at least >>> s1="python3"
1 character and all characters are >>> s1.isalnum()
alphanumeric and false True
otherwise.
>>> s1="1234"
>>> s1.isalnum()
True
>>> s1="python programming"
>>> s1.isalnum()
False
12. isalpha() Returns true if string has at least >>> s1="python"
1 character and all characters are #no space and digit in this
alphabetic and false otherwise. string
>>> s1.isalpha()
True
>>> s1="python3"
>>> s1.isalpha()
False
>>> s1="python programming"
>>> s1.isalpha()
False
13. isdigit() Returns true if string contains >>> s1="python programming"
only digits and false otherwise. >>> s1.isdigit()
False
>>> s1="python3"
>>> s1.isdigit()
False
>>> s1="12345"
#only digit in string
>>> s1.isdigit()
True
14. islower() Returns true if string has at least >>> s1="python"
1 cased character and all cased >>> s1.islower()
characters are in lowercase and True
false otherwise.
>>> s1="Python"
>>> s1.islower()
False
contd. …
Programming with 'Python' 3.35 Data Structures in Python
Practice Questions
1. What is data structure? Which data structure used by Python?
2. How to define and access the elements of list?
3. What is list? How to create list?
4. What are the different operations that can be performed on a list? Explain with examples
5. Explain any two methods under lists in Python with examples.
6. Write a Python program to describe different ways of deleting an element from the given List.
7. What is tuple in Python? How to create and access it?
8. What are mutable and immutable types?
Programming with 'Python' 3.36 Data Structures in Python
Learning Objectives…
▣ To learn Basic Concepts of Functions
▣ To study use of Python Built-in Functions
▣ To understand User Defined Functions with its Definition, Calling, Arguments Passing etc.
▣ To study Scope of Variables like Global and Local
▣ To learn Module Concept with Writing and Importing Modules
▣ To study Python Built-in Modules like Numeric, Mathematical, Functional Programming Module
▣ To learn Python Packages with its Basic Concepts and User Defined Packages
4.0 INTRODUCTION
• Functions, modules and packages are all constructs in Python programming that promote code
modularization. The modularization (modular programming) refers to the process of breaking a
large programming task into separate, smaller, more manageable subtasks or modules.
• A function is a block of organized, reusable code that is used to perform a single, related
action/operation. Python has excellent support for functions.
• A function can be defined as the organized block of reusable code which can be called whenever
required. A function is a piece of code that performs a particular task.
• A function is a block of code which only runs when it is called. Python gives us many built-in
functions like print() but we can also create our own functions called as user-defined functions.
• A module in Python programming allows us to logically organize the python code. A module is a
single source code file. The module in Python have the .py file extension. The name of the module
will be the name of the file.
• A python module can be defined as a python program file which contains a python code including
python functions, class, or variables. In other words, we can say that our Python code file saved with
the extension (.py) is treated as the module.
• In Python, packages allow us to create a hierarchical file directory structure of modules. For
example, mymodule.mod1 stands for a module mod1, in the package mymodule.
• A Python package is a collection of modules which have a common purpose. In short, modules are
grouped together to forms packages.
[4.1]
Programming with 'Python' 4.2 Python Functions, Modules and Packages
2. Formal Parameters:
• The parameters used in the header of function definition are called formal parameters of the
function. These parameters are used to receive values from the calling function.
(i) They are used in the function header.
(ii) They are used to receive the values that are passed to the function through function call.
(iii) They are treated as local variables of a function in which they are used in the function header.
Example: For actual and formal parameters.
>>> def cube(x): # formal parameters
return x*x*x
a 3
• When control comes to n =n+1 as integer is immutable, by definition we are not able to modify the
object’s value to 4 in place: we must create a new object with the value 4. We may visualize it like
below:
n 4
• All this time, the variable a continues to refer to the object with the value 3, since we did not change
the reference:
a
s 3
• We can still “modify” immutable objects by capturing the return of the function.
>>> def increment(n):
n
n=n+1
return n
>>> a=3
>>> a=increment(3)
>>> print(a)
4
Programming with 'Python' 4.9 Python Functions, Modules and Packages
• By assigning the return value of the function to a, we have reassigned a to refer to the new object
with the value 4 created in the function. Note the object a initially referred to never change — it is
still 3 — but by having a point to a new object created by the function, we are able to “modify” the
value of a.
• The same increment() function generates a different result when we passing a mutable object: Here L
is a list which is mutable
>>> def increment(n):
n.append([4])
>>> L=[1,2,3]
>>> increment(L)
>>> print(L)
[1, 2, 3, [4]]
• Here, the statement L = [1,2,3] makes a variable L(box) that points towards the object [1,2,3].
• On the function being called, a new box n is created. The contents of n are the SAME as the contents
of box L. Both the boxes contain the same object. That is, both the variables point to the same object in
memory. Hence, any change to the object pointed at by n will also be reflected by the object pointed
at by L.
n 1 2 3 4
• A function is said to be a recursive if it calls itself. For example, lets say we have a function abc() and
in the body of abc() there is a call to the abc().
Example: For recursive function.
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
print(fact(0))
print(fact(4))
print(fact(6))
Output:
1
24
720
• The factorial of 4 (denoted as 4!) is 1*2*3*4 = 24.
• Each function call multiples the number with the factorial of number 1 until the number is equal to
one.
fact(4) # 1st call with 4
4 * fact(3) # 2nd call with 3
4 * 3 * fact(2) # 3rd call with 2
4 * 3 * 2 * fact(1) # 4th call with 1
4 * 3 * 2 * 1 # return from 4th call as number=1
4 * 3 * 2 # return from 3rd call
4 * 6 # return from 2nd call
24 # return from 1st call
• Our recursion ends when the number reduces to 1. This is called the base condition. Every recursive
function must have a base condition that stops the recursion or else the function calls itself
infinitely.
Advantages of Recursion:
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion:
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
4. It consumes more storage space because the recursive calls along with variables are stored on the
stack.
5. It is not more efficient in terms of speed and execution time.
Example: Programs to convert U.S. dollars to Indian rupees.
def dol_rup():
dollars = float(input("Please enter dollars:"))
rupees = dollars * 70
print("Dollars: ",dollars)
print("Rupees: ",rupees)
def euro_rup():
euro= float(input("Please enter euro:"))
rupees = euro * 79.30
print("Euro: ",euro)
print("Rupees: ",rupees)
Programming with 'Python' 4.14 Python Functions, Modules and Packages
def menu():
print("1: Doller to Rupees")
print("2: Euro to Rupees")
print("3: Exit")
choice=int(input("Enter your choice: "))
if choice==1:
dol_rup()
if choice==2:
euro_rup()
if choice==3:
print("Good bye!")
menu()
Output:
1: Doller to Rupees
2: Euro to Rupees
3: Exit
Enter your choice: 1
Please enter dollars:75
Dollars: 75.0
Rupees: 5250.0
4.3 MODULES
• Modules are primarily the (.py) files which contain Python programming code defining functions,
class, variables, etc. with a suffix .py appended in its file name. A file containing .py python code is
called a module.
• If we want to write a longer program, we can use file where we can do editing, correction. This is
known as creating a script. As the program gets longer, we may want to split it into several files for
easier maintenance.
• We may also want to use a function that we have written in several programs without copying its
definition into each program.
• In Python we can put definitions in a file and use them in a script or in an interactive instance of the
interpreter. Such a file is called a module.
4.3.1 Writing Module
• Writing a module means simply creating a file which can contains python definitions and
statements. The file name is the module name with the extension .py. To include module in a file,
use import statement.
• Follow the following steps to create modules:
1. Create a first file as a python program with extension as .py. This is your module file where we
can write a function which perform some task.
2. Create a second file in the same directory called main file where we can import the module to the
top of the file and call the function.
• Second file needs to be in the same directory so that Python knows where to find the module since
it’s not a built-in module.
Example: For creating a module. Type the following code and save it as p1.py.
def add(a, b):
"This function adds two numbers and return the result"
result = a + b
return result
def sub(a, b):
"This function subtract two numbers and return the result"
result = a - b
return result
Programming with 'Python' 4.15 Python Functions, Modules and Packages
2. Decimal Module:
• Decimal numbers are just the floating-point numbers with fixed decimal points. We can create
decimals from integers, strings, floats, or tuples.
• A Decimal instance can represent any number exactly, round up or down, and apply a limit to the
number of significant digits.
Example : For decimal module.
>>> from decimal import Decimal
>>> Decimal(121)
Decimal('121')
>>> Decimal(0.05)
Decimal('0.05000000000000000277555756156289135105907917022705078125')
>>> Decimal('0.15')
Decimal('0.15')
>>> Decimal('0.012')+Decimal('0.2')
Decimal('0.212')
>>> Decimal(72)/Decimal(7)
Decimal('10.28571428571428571428571429')
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724')
3. Fractions Module:
• A fraction is a number which represents a whole number being divided into multiple parts. Python
fractions module allows us to manage fractions in our Python programs.
• Example: For fractions module.
>>> import fractions
>>> for num, decimal in [(3, 2), (2, 5), (30, 4)]:
fract = fractions.Fraction(num, decimal)
print(fract)
3/2
2/5
15/2
• It is also possible to convert a decimal into a Fractional number. Let’s look at a code snippet:
>>> import fractions
>>> for deci in ['0.6', '2.5', '2.3', '4e-1']:
fract = fractions.Fraction(deci)
print(fract)
Output:
3/5
5/2
23/10
2/5
>>>
4. Random Module:
• Sometimes, we want the computer to pick a random number in a given range, pick a random
element from a list etc.
• The random module provides functions to perform these types of operations. This function is not
accessible directly, so we need to import random module and then we need to call this function using
random static object.
• Example: For random module.
>>> import random
>>> print(random.random()) # It generate a random number in the range (0.0, 1.0)
0.27958089234907935
>>> print(random.randint(10,20)) # It generate a random integer between x and y inclusive
13
Programming with 'Python' 4.20 Python Functions, Modules and Packages
5. Statistics Module:
• Statistics module provides access to different statistics functions. Example includes mean (average
value), median (middle value), mode (most often value), standard deviation (spread of values).
• Example: For statistics module.
>>> import statistics
>>> statistics.mean([2,5,6,9]) # average
5.5
>>> import statistics
>>> statistics.median([1,2,3,8,9]) # central value
3
>>> statistics.median([1,2,3,7,8,9])
5.0
>>> import statistics
>>> statistics.mode([2,5,3,2,8,3,9,4,2,5,6]) # repeated value
2
>>> import statistics
>>> statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5])
1.3693063937629153
(II) Functional Programming Modules:
• These modules provide functions and classes that support a functional programming style and
general operations on callables.
• Following are modules which comes under functional programming modules.
(i) itertools (functions creating iterators for efficient looping).
(ii) functools (higher-order functions and operations on callable objects).
(iii) operator (standard operators as functions).
1. itertools Module:
• Python programming itertools module provide us various ways to manipulate the sequence while we
are traversing it.
• Python itertools chain() function just accepts multiple iterable and return a single sequence as if all
items belongs to that sequence.
• Example: For itertools module with chain().
>>> from itertools import *
>>> for value in chain([1.3, 2.51, 3.3], ['C++', 'Python', 'Java']):
print(value)
Output:
1.3
2.51
3.3
C++
Python
Java
• Python itertools cycle() function iterate through a sequence upto infinite. This works just like a
circular Linked List.
• Example: For intools module with cycles().
>>> from itertools import *
>>> for item in cycle(['C++','Python','Java']):
index=index+1
if index==10:
break
print(item)
Programming with 'Python' 4.21 Python Functions, Modules and Packages
Output:
C++
Python
Java
C++
Python
Java
C++
Python
Java
>>>
2. functools Module:
• Python functools module provides us various tools which allows and encourages us to write reusable
code.
• Python functools partial() functions are used to replicate existing functions with some arguments
already passed in. It also creats new version of the function in a well-documented manner.
• Suppose we have a function called multiplier which just multiplies two numbers. Its definition looks
like:
def multiplier(x, y):
return x * y
• Now, if we want to make some dedicated functions to double or triple a number then we will have to
define new functions as:
def multiplier(x, y):
return x * y
def doubleIt(x):
return multiplier(x, 2)
def tripleIt(x):
return multiplier(x, 3)
• But what happens when we need 1000 such functions? Here, we can use partial functions:
from functools import partial
def multiplier(x, y):
return x * y
double = partial(multiplier, y=2)
triple = partial(multiplier, y=3)
print('Double of 2 is {}'.format(double(5)))
print('Triple of 5 is {}'.format(triple(5)))
Output:
Double of 5 is 10
Triple of 5 is 15
3. Operator Module:
• The operator module supplies functions that are equivalent to Python’s operators. These functions
are handy in cases where callables must be stored, passed as arguments, or returned as function
results.
• Functions supplied by the operator module are listed in following table:
Sr. No. Function Signature/Syntax Behaves Like
1. abs abs(a) abs(a)
2. add add(a,b) a+b
3. and_ and_(a,b) a&b
4. div div(a,b) a/b
contd. …
Programming with 'Python' 4.22 Python Functions, Modules and Packages
5. eq eq(a,b) a==b
6. gt gt(a,b) a>b
7. invert, inv invert(a), inv(a) ~a
8. le le(a,b) a<=b
9. lshift lshift(a,b) a<<b
10. lt lt(a,b) a<b
11. mod mod(a,b) a%b
12. mul mul(a,b) a*b
13. ne ne(a,b) a!=b
14. neg neg(a) -a
15. not_ not_(a) not a
16. or_ or_(a,b) a|b
17. pos pos(a) +a
18. repeat repeat(a,b) a*b
19. rshift rshift(a,b) a>>b
20. xor_ xor(a,b) a^b
• Namespaces help us uniquely identify all the names inside a program. According to Python's
documentation “a scope is a textual region of a Python program, where a namespace is directly
accessible.” Directly accessible means that when we are looking for an unqualified reference to a
name Python tries to find it in the namespace.
• Scopes are determined statically, but actually, during runtime, they are used dynamically. This
means that by inspecting the source code, we can tell what the scope of an object is, but this does not
prevent the software from altering that during runtime.
Python Variable Scoping:
• Scope is the portion of the program from where a namespace can be accessed directly without any
prefix.
• Namespaces are a logical way to organize variable names when a variable inside a function (a local
variable) shares the same name as a variable outside of the function (a global variable).
• Local variables contained within a function (either in the script or within an imported module) and
global variables can share a name as long as they do not share a namespace.
• At any given moment, there are at least following three nested scopes:
1. Scope of the current function which has local names.
2. Scope of the module which has global names.
3. Outermost scope which has built-in names.
• When a reference is made inside a function, the name is searched in the local namespace, then in the
global namespace and finally in the built-in namespace.
• If there is a function inside another function, a new scope is nested inside the local scope. Python has
two scopes.
1. Local Scope Variable: All those variables which are assigned inside a function known as local
scope Variable
2. Global Scope Variable: All those variables which are outside the function termed as global
variable.
Example: For global scope and local scope.
global_var = 30 # global scope
def scope():
local_var = 40 # local scope
print(global_var)
print(local_var)
scope()
print(global_var)
Output:
30
40
3
• It extends the capabilities of NumPy with further useful functions for minimization, regression,
Fourier-transformation and many others.
• Both NumPy and SciPy are not part of a basic Python installation. They have to be installed after the
Python installation. NumPy has to be installed before installing SciPy.
4.4.3.1 Math
• Some of the most popular mathematical functions are defined in the math module. These include
trigonometric functions, representation functions, logarithmic functions and angle conversion
functions.
• Two mathematical constants are also defined in math module.
• Pie (π
π) is a well-known mathematical constant, which is defined as the ratio of the circumference to
the diameter of a circle and its value is 3.141592653589793.
>>> import math
>>> math.pi
3.141592653589793
>>>
• Another well-known mathematical constant defined in the math module is e. It is called Euler's
number and it is a base of the natural logarithm. Its value is 2.718281828459045.
>>> import math
>>> math.e
2.718281828459045
>>>
• Different mathematical functions of Math module already explained in Section 4.1.2.
4.4.3.2 NumPy
• NumPy is the fundamental package for scientific computing with Python. NumPy stands for
"Numerical Python". It provides a high-performance multidimensional array object, and tools for
working with these arrays.
• An array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive
integers and represented by a single variable. NumPy's array class is called ndarray. It is also known
by the alias array.
• In NumPy arrays, the individual data items are called elements. All elements of an array should be of
the same type. Arrays can be made up of any number of dimensions.
• In NumPy, dimensions are called axes. Each dimension of an array has a length which is the total
number of elements in that direction.
• The size of an array is the total number of elements contained in an array in all the dimension. The
size of NumPy arrays are fixed; once created it cannot be changed again.
• Numpy arrays are great alternatives to Python Lists. Some of the key advantages of Numpy arrays
are that they are fast, easy to work with, and give users the opportunity to perform calculations
across entire arrays.
• Fig. 4.6 shows the axes (or dimensions) and lengths of two example arrays; (a) is a one-dimensional
array and (b) is a two-dimensional array.
Length = 3
2
4
Axis - 0
1
Length = 5
3 0
Axis - 0
2 0 1 2 3 4 5
1
Columns
0 Axis-1
(a) (b)
Fig. 4.6: Dimensions of NumPy Array
Programming with 'Python' 4.26 Python Functions, Modules and Packages
• A one dimensional array has one axis indicated by Axis-0. That axis has five elements in it, so we say
it has length of five.
• A two dimensional array is made up of rows and columns. All rows are indicated by Axis-0 and all
columns are indicated by Axis-1. If Axis-0 in two dimensional array has three elements, so its length
it three and Axis-1 has six elements, so its length is six.
• Execute Following command to install numpy in window, Linux and MAC OS:
python -m pip install numpy
• To use NumPy you need to import Numpy:
import numpy as np # alias np
• Using NumPy, a developer can perform the following operations:
1. Mathematical and logical operations on arrays.
2. Fourier transforms and routines for shape manipulation.
3. Operations related to linear algebra.
4. NumPy has in-built functions for linear algebra and random number generation.
Array Object:
• NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually
numbers), all of the same type, indexed by a tuple of positive integers.
• In NumPy dimensions are called axes. The number of axes is rank. NumPy’s array class is called
ndarray. It is also known by the alias array.
• Basic attributes of the ndarray class as follow:
Sr. No. Attributes Description
1. shape A tuple that specifies the number of elements for each dimension of the array.
2. size The total number elements in the array.
3. ndim Determines the dimension an array.
4. nbytes Number of bytes used to store the data.
5. dtype Determines the datatype of elements stored in array.
Fig. 4.7
Example:
>>> arr=np.array([[1,2,3],[4,5,6]])
>>> a=arr.reshape(3,2)
>>> a
array([[1, 2],
[3, 4],
[5, 6]])
Slicing of Array:
• Slicing is basically extracting particular set of elements from an array. Consider an array
([(1,2,3,4), (5,6,7,8)]).
• Here, the array (1,2,3,4) is at index 0 and (3,4,5,6) is at index 1 of the python numpy array. We need a
particular element (say 3) out of a given array.
Programming with 'Python' 4.28 Python Functions, Modules and Packages
Addint/Removing
Elements Description
Elements
resize Returns a new array with the specified shape.
append Appends the values to the end of the array.
insert Inserts the value along the given axis before the given
indices.
delete Returns a new array with sub array along an axis deleted.
unique Finds the unique elements in the array.
Bitwise Operation Description
Operations
bitwise_and Compute bitwise AND operation of array elements.
bitwise_or Compute bitwise OR operation of array elements.
invert Compute bitwise NOT.
left_shift Shifts bits of a binary representation to the left.
right_shift Shifts bits of a binary representation to the right.
• Using numpy, we can deal with 1D polynomials by using the class poly1d. This class takes
coefficients or roots for initialization and forms a polynomial object. When we print this object we
will see it prints like a polynomial.
• Let us have a look at example code:
from numpy import poly1d
poly1 = poly1d([1,2,3])
print(poly1)
print("\nSquaring the polynomial: \n")
print(poly1* poly1)
print("\nIntegrating the polynomial: \n")
print(poly1.integ(k=3))
print("\nFinding derivative of the polynomial: \n")
print(poly1.deriv())
print("\nSolving the polynomial for 2: \n")
print(poly1(2))
Output:
2
1 x + 2 x + 3
Squaring the polynomial:
4 3 2
1 x + 4 x + 10 x + 12 x + 9
Integrating the polynomial:
3 2
0.3333 x + 1 x + 3 x + 3
Finding derivative of the polynomial:
2 x + 2
Solving the polynomial for 2:
11
Programming with 'Python' 4.30 Python Functions, Modules and Packages
4.4.3.3 SciPy
• SciPy is a library that uses NumPy for more mathematical functions. SciPy uses NumPy arrays as the
basic data structure, and comes with modules for various commonly used tasks in scientific
programming, including linear algebra, integration (calculus), ordinary differential equation
solving, and signal processing.
• Following command execute to install SciPy in Window, Linux and MAC OS:
python -m pip install scipy
• SciPy is organized into subpackages covering different scientific computing domains. These are
summarized in the following table:
Sr. No. Subpackage Description
1. cluster Clustering algorithms.
4.4.3.4 Matplotlib
• matplotlib.pyplot is a plotting library used for 2D graphics in python programming language. It can
be used in python scripts, shell, web application servers and other graphical user interface toolkits.
• There are various plots which can be created using python matplotlib like bar graph, histogram,
scatter plot, area plot, pie plot.
• Following command execute to install matplotlib in Window, Linux and MAC OS:
python –m pip install matplotlib
Importing matplotlib:
from matplotlib import pyplot as plt
OR
import matplotlib.pyplot as plt
Example: For line plot.
>>> from matplotlib import pyplot as plt
>>> x=[2,4,8,10]
>>> y=[2,8,8,2]
>>> plt.plot(x,y)
[<matplotlib.lines.Line2D object at 0x02E69B70>]
>>> plt.show()
Output:
Bar Graph:
• A bar graph uses bars to compare data among different categories. It is well suited when you want to
measure the changes over a period of time. It can be represented horizontally or vertically.
Example: For bar graph.
>>> from matplotlib import pyplot as plt
>>> x=[2,4,8,10]
>>> y=[2,8,8,2]
>>> plt.xlabel('X-Axis')
Text(0.5, 0, 'X-Axis')
>>> plt.ylabel('Y-Axis')
Text(0, 0.5, 'Y-Axis')
>>> plt.title('Graph')
Text(0.5, 1.0, 'Graph')
>>> plt.bar(x,y,label="Graph",color='r',width=.5)
<BarContainer object of 4 artists>
>>> plt.show()
Programming with 'Python' 4.32 Python Functions, Modules and Packages
Output:
Histogram:
• Histograms are used to show a distribution whereas a bar chart is used to compare different entities.
Histograms are useful when we have arrays or a very long list.
• A Histogram is a special graph that uses vertical columns to show frequencies (how many times each
score occurs):
Example: For histogram.
>>> from matplotlib import pyplot as plt
>>> y=[1,1,2,2,2,2,2,3,3,3,3,4,4,5]
>>> plt.hist(y)
(array([2., 0., 5., 0., 0., 4., 0., 2., 0., 1.]), array([1. , 1.4, 1.8, 2.2, 2.6,
3. , 3.4, 3.8, 4.2, 4.6, 5. ]), <a list of 10 Patch objects>)
>>> plt.show()
Output:
Scatter Plot:
• Usually we need scatter plots in order to compare variables, for example, how much one variable is
affected by another variable to build a relation out of it.
• The data is displayed as a collection of points, each having the value of one variable which
determines the position on the horizontal axis and the value of other variable determines the
position on the vertical axis.
Example: For scatter plot.
>>> from matplotlib import pyplot as plt
>>> x = [5, 2, 9, 4, 7]
>>> y = [10, 5, 8, 4, 2]
>>> plt.scatter(x,y)
<matplotlib.collections.PathCollection object at 0x05792770>
>>> plt.show()
Programming with 'Python' 4.33 Python Functions, Modules and Packages
Output:
4.4.3.5 Pandas
• Pandas is an open-source Python Library providing high-performance data manipulation and
analysis tool using its powerful data structures.
• It is built on the Numpy package and its key data structure is called the DataFrame. DataFrames
allow you to store and manipulate tabular data in rows of observations and columns of variables.
Installing Pandas:
pip install pandas
Data structures supported by Pandas:
• Pandas deals with the following three data structures:
Sr. No. Data Structure Dimensions Description
1. Series 1 1D labeled homogeneous array, size immutable.
2. Data Frames 2 General 2D labeled, size-mutable tabular structure
with potentially heterogeneously typed columns.
3. Panel 3 General 3D labeled, size-mutable array.
Series:
• Series is a one-dimensional array like structure with homogeneous data. The Series is a one
dimensional array which is Labelled and it is capable of holding array of any type like Integer, Float,
String and Python Objects.
• For example, the following series is a collection of integers 10, 22, 30, 40,… The syntax is as follows:
pandas.Series(data, index, dtype, copy)
• It takes four arguments:
1. data: It is the array that needs to be passed so as to convert it into a series. This can be Python
lists, NumPy Array or a Python Dictionary or Constants.
2. index: This holds the index values for each element passed in data. If it is not specified, default
is numpy.arange(length_of_data).
3. dtype: It is the datatype of the data passed in the method.
4. copy: It takes a Boolean value specifying whether or not to copy the data. If not specified, default
is false.
• Here data is only mandatory argument of Series.
Example 1: Using Series data structure of Panda.
>>> import pandas as pd
>>> import numpy as np
>>> numpy_arr = array([2, 4, 6, 8, 10, 20])
>>> si = pd.Series(arr)
>>> print(si)
Programming with 'Python' 4.34 Python Functions, Modules and Packages
0 2
1 4
2 6
3 8
4 10
5 20
dtype: int32
Example 2: Using Series data structure of Panda.
>>> import pandas as pd
>>> data=[10,20,30,40,50]
>>> index=['a','b','c','d','e']
>>> si=pd.Series(data,index)
>>> si
a 10
b 20
c 30
d 40
e 50
dtype: int64
>>>
Data Frames:
• Data Frame is a two-dimensional array with heterogeneous data. We can convert a Python’s list,
dictionary or Numpy array to a Pandas data frame.
• For example:
Roll No Name City
11 Vijay Thane
12 Amar Pune
13 Santosh Mumbai
pandas.DataFrame(data, index, columns, dtype, copy)
• It takes following arguments:
1. data: The data that is needed to be passed to the DataFrame() Method can be of any form line
ndarray, series, map, dictionary, lists, constants and another DataFrame.
2. index: This argument holds the index value of each element in the DataFrame. The default index
is np.arange(n).
3. columns: The default values for columns is np.arange(n).
4. dtype: This is the data type of the data passed in the method.
5. copy: It takes a Boolean value to specify whether or not to copy the data. The default value
is false.
• Here data is only mandatory argument of DataFrame.
Example:
>>> import pandas as pd
>>> li = [1, 2, 3, 4, 5, 6]
>>> df = pd.DataFrame(li)
>>> print(df)
0 1
1 2
2 3
3 4
4 5
5 6
Programming with 'Python' 4.35 Python Functions, Modules and Packages
• The specified functions can now be imported in the interpreter session or another executable script.
Create test.py in the MyPkg folder and write following code:
test.py
from MyPkg import power, average, SayHello
SayHello()
x=power(3,2)
print("power(3,2) : ", x)
• Note that functions power() and SayHello() are imported from the package and not from their
respective modules, as done earlier. The output of above script is:
Hello world
power(3,2) : 9
Practice Questions
1. What is function?
2. What is module?
3. What is package?
4. Define function. Write syntax to define function. Give example of function definition.
5. Can a Python function return multiple values? If yes, how it works?
6. How function is defined and called in Python.
7. Explain about void functions with suitable examples.
8. What is actual and formal parameter? Explain the difference along with example.
9. Explain about fruitful functions with suitable examples.
10. Discuss the difference between local and global variable.
11. Explain any five basic operations performed on string.
12. Explain math module with its any five functions.
13. Differentiate between match() and search() function. Explain with example.
14. Explain type conversion of variable in Python.
15. Write a function that takes single character and prints ‘character is vowel’ if it is vowel,
‘character is not vowel’ otherwise.
16. Explain various string operations that can be performed using operators in Python.
17. Explain with an example, how + and * operators work with strings.
18. Explain str.find() function with suitable example.
19. Define is module? What are the advantages of using module?
20. How to create a module and use it in a python program explain with an example.
21. Explain various functions of math module.
22. List and explain any four built in string manipulation functions supported by Python.
23. Explain string slicing in Pyhton. Show with example.
24. Explain the concept of namespaces with an example.
25. Write about the concept of scope of a variable in a function.
Programming with 'Python' 4.38 Python Functions, Modules and Packages
Learning Objectives…
[
5.0 INTRODUCTION
• Python is an Object-Oriented Programming Language (OOPL) follows an Object-Oriented
Programming (OOP) paradigm. It deals with declaring Python classes and objects which lays the
foundation of OOPs concepts.
• Python programming offers OOP style programming and provides an easy way to develop programs.
Python programming uses the OOPs concepts that makes Python more powerful to help design a
program that represents real-world entities.
• Python also supports OOP concepts such as Inheritance, Method overriding, Data abstraction and
Data hiding.
Important terms in OOP/Terminology of OOP:
1. Class: Classes are defined by the user. The class provides the basic structure for an object. It
consists of data members and method members that are used by the instances, (objects) of the
class.
2. Object: A unique instance of a data structure that is defined by its class. An object comprises
both data members (class variables and instance variables) and methods. Class itself does
nothing but the real functionality is achieved through their objects. Object is an instance or
occurrence of the class. It takes the properties (variables) and uses the behavior (methods)
defined in the class.
3. Data Member: A variable defined in either a class or an object; it holds the data associated with
the class or object.
4. Instance Variable: A variable that is defined in a method; it scope is only within the object that
defines it.
5. Class Variable: A variable that is defined in the class and can be used by all the instances of that
class.
[5.1]
Programming with 'Python' 5.2 Object Oriented Programming in Python
c1= Counter()
c1.count() #invoke method
c1.count()
print ("Total count=",c1._ _secretCount) #cannot access private variable directly
Output:
count= 1
count= 2
AttributeError: 'Counter' object has no attribute '_ _secretCount'
Programming with 'Python' 5.5 Object Oriented Programming in Python
Constructor:
• A constructor is a special method i.e., is used to initialize the instance variable of a class.
Creating Constructor in Class:
• A constructor is a special type of method (function) which is used to initialize the instance members
of the class.
• Constructors are generally used for instantiating an object. The task of constructors is to initialize
(assign values) to the data members of the class when an object of class is created.
• Python class constructor is the first piece of code to be executed when we create a new object of a
class.
• In Python the _ _init_ _() method is called the constructor and is always called when an object is
created.
• Primarily, the constructor can be used to put values in the member variables. We may also print
messages in the constructor to be confirmed whether the object has been created.
Syntax:
def _ _init_ _(self):
# body of the constructor
• _ _init_ _ is a special method in Python classes, which is the constructor method for a class. In the
following example you can see how to use it.
Example 1: For creating constructor.
class Person:
def _ _init_ _(self, rollno, name, age):
self.rollno=rollno
self.name = name
self.age = age
print("Student object is created")
p1 = Person(11,"Vijay", 40)
print("Rollno of student= ", p1.rollno)
print("Name of student= ",p1.name)
print("Age of student= ",p1.age)
Output:
Student object is created
Rollno of student= 11
Name of student= Vijay
Age of student= 40
Example 2: Define a class named Rectangle which can be constructed by a length and width. The
Rectangle class has a method which can compute the area.
class Rectangle(object):
def _ _init_ _(self, l, w):
self.length = l
self.width = w
def area(self):
return self.length*self.width
r = Rectangle(2,10)
print(r.area())
Output:
20
Programming with 'Python' 5.7 Object Oriented Programming in Python
Example 3: Create a Cricle class and intialize it with radius. Make two methods getArea and
getCircumference inside this class.
class Circle():
def _ _init_ _(self,radius):
self.radius = radius
def getArea(self):
return 3.14*self.radius*self.radius
def getCircumference(self):
return self.radius*2*3.14
c=Circle(5)
print("Area",c.getArea())
print("Circumference",c.getCircumference())
Output:
Area 78.5
Circumference 31.400000000000002
• The types of constructors includes default constructor and parameterized constructor.
1. Default Constructor:
• The default constructor is simple constructor which does not accept any arguments. It’s definition
has only one argument which is a reference to the instance being constructed.
Example 1: Display Hello message using default constructor.
class Student:
def _ _init_ _(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
s1 = Student()
s1.show("Meenakshi")
Output:
This is non parametrized constructor
Hello Meenakshi
Example 2: Counting the number of objects of a class.
class Student:
count=0;
def _ _init_ _(self):
Student.count=Student.count+1
s1=Student()
s2=Student()
print("The number of student objects",Student.count)
Output:
The number of student objects: 2
2. Parameterized Constructor:
• Constructor with parameters is known as parameterized constructor.
• The parameterized constructor take its first argument as a reference to the instance being
constructed known as self and the rest of the arguments are provided by the programmer.
Example: For parameterized constructor.
class Student:
def _ _init_ _(self,name):
print("This is parametrized constructor")
self.name = name
Programming with 'Python' 5.8 Object Oriented Programming in Python
def show(self):
print("Hello",self.name)
s1 = Student("Meenakshi")
s1.show()
Output:
This is parametrized constructor
Hello Meenakshi
Destructor:
• A class can define a special method called a destructor with the help of _ _del_ _(). It is invoked
automatically when the instance (object) is about to be destroyed.
• It is mostly used to clean up any non-memory resources used by an instance (object).
Example: For destructor.
class Student:
def __init__(self):
print('non parameterized constructor-student created ')
def __del__(self):
print('Destructor called, student deleted.')
s1=Student()
s2=Student()
del s1
Output:
non parameterized constructor-student created
non parameterized constructor-student created
Destructor called, student deleted.
Built-in Class Attributes:
• Every Python class keeps following built-in attributes and they can be accessed using dot operator
like any other attribute:
o _ _dict_ _: It displays the dictionary in which the class’s namespace is stored.
o _ _name_ _: It displays the name of the class.
o _ _bases_ _: It displays the tuple that contains the base classes, possibly empty. It displays them
in the order in which they occur in the base class list.
o _ _doc_ _: It displays the documentation string of the class. It displays none if the docstring isn’t
given.
o _ _module_ _: It displays the name of the module in which the class is defined. Generally the
value of this attributes is “_ _main_ _” in interactive mode.
Example: For default built-in class attribute.
class test:
'This is a sample class called Test.'
def _ _init_ _(self):
print("Hello from _ _init_ _ method.")
# class built-in attribute
print(test._ _doc_ _)
print(test._ _name_ _)
print(test._ _module_ _)
print(test._ _bases_ _)
print(test._ _dict_ _)
Programming with 'Python' 5.9 Object Oriented Programming in Python
Output:
This is a class called Test.
test
_ _main_ _
(<class 'object'>,)
{'_ _module_ _': '_ _main_ _', '_ _doc_ _': 'This is a sample class called Test.',
'_ _init_ _': <function test._ _init_ _ at 0x013AC618>, '_ _dict_ _': <attribute
'_ _dict_ _' of 'test' objects>, '_ _weakref_ _': <attribute '_ _weakref_ _' of
'test' objects>}
• Same method works for three different data types. Thus, we cannot define two methods with the
same name and same number of arguments but having different type as shown in the above
example. They will be treated as the same method.
• It is clear that method overloading is not supported in python but that does not mean that we cannot
call a method with different number of arguments. There are a couple of alternatives available in
python that make it possible to call the same method but with different number of arguments.
Using Default Arguments:
• It is possible to provide default values to method arguments while defining a method. If method
arguments are supplied default values, then it is not mandatory to supply those arguments while
calling method as shown in next example.
Example 1: Method overloading with default arguments.
class Demo:
def arguments(self, a = None, b = None, c = None):
if(a != None and b != None and c != None):
print("3 arguments")
elif (a != None and b != None):
print("2 arguments")
elif a != None:
print("1 argument")
else:
print("0 arguments")
obj = Demo()
obj.arguments("Meenakshi","Anurag","Thalor")
obj.arguments("Anurag","Thalor")
obj.arguments("Thalor")
obj.arguments()
Output:
3 arguments
2 arguments
1 argument
0 arguments
Example 2: With a method to perform different operations using method overloading.
class operation:
def add(self,a,b):
return a+b
op1=operation()
# To add two integer numbers
print("Addition of integer numbers=",op1.add(10,20))
# To add two floting point numbers
print("Addition of integer numbers=",op1.add(11.12,12.13))
# To add two strings
print("Addition of integer numbers=",op1.add("Hello","Python"))
Output:
Addition of integer numbers= 30
Addition of integer numbers= 23.25
Addition of integer numbers= HelloPython
5.5.1 Inheritance
• In inheritance objects of one class procure the properties of objects of another class. Inheritance
provide code reusability, which means that some of the new features can be added to the code while
using the existing code. The mechanism of designing or constructing classes from other classes is
called inheritance.
• The new class is called derived class or child class and 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: Base Class Class A
class A:
# properties of class A
class B(A): Derived Class Class B
# class B inheriting property of class A
Fig. 5.1: Concept of Inheritance
# more properties of class B (Single Inheritance)
Output:
Name= Maruti
Price=$ 2000
Name= BMW
Price=$ 5000
Multilevel Inheritance:
• Multi-level inheritance is archived when a derived class inherits another
derived class. There is no limit on the number of levels up to which, the Class A
multi-level inheritance is archived in python.
• In multilevel inheritance (See Fig. 5.2), we inherit the classes at multiple
Class B
separate levels. We have three classes A, B and C, where A is the super
class, B is its sub(child) class and C is the sub class of B.
Syntax: Class C
class A:
Fig. 5.2
# properties of class A
class B(A):
# class B inheriting property of class A
# more properties of class B
class C(B):
# class C inheriting property of class B
# thus, class C also inherits properties of class A
# more properties of class C
Example: For multilevel inheritance.
class Grandfather:
def display1(self):
print("Grand Father")
# The child class Father inherits the base class Grandfather
class Father(Grandfather):
def display2(self):
print("Father")
# The child class Son inherits another child class Father
class Son(Father):
def display3(self):
print("Son")
s1=Son()
s1.display3()
s1.display2()
s1.display1()
Output:
Son
Father
Grand Father
Multiple Inheritance:
• Python provides us the flexibility to inherit multiple base classes in the child class.
• Multiple Inheritance means that we are inheriting the property of multiple classes into one. In case
we have two classes, say A and B, and we 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.
Programming with 'Python' 5.13 Object Oriented Programming in Python
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 classA and B
# add more properties to class C
Base Class 1 Base Class 2 Base Class 3 Class A Class B
(a) (b)
Fig. 5.3
Example:
# base class
class Father:
def display1(self):
print("Father")
# base class
class Mother:
def display2(self):
print("Mother")
# derived class
class Son(Father,Mother):
def display3(self):
print("Son")
s1=Son()
s1.display3()
s1.display2()
s1.display1()
Output:
Son
Mother
Father
Hierarchical Inheritance: Class A
• When more than one derived classes are created from a
single base – it is called hierarchical inheritance.
• In following program, we have a parent (base) class name
Email and two child (derived) classes named Gmail and Class B Class C
yahoo.
Fig. 5.4
Example: For hierarchical inheritance.
class Email:
def send_email(self, msg):
print()
class Gmail(Email):
def send_email(self, msg):
print( "Sending `{}` from Gmail".format(msg) )
Programming with 'Python' 5.14 Object Oriented Programming in Python
class Yahoo(Email):
def send_email(self, msg):
print( "Sending `{}` from Yahoo".format(msg) )
client1 = Gmail()
client1.send_email("Hello!")
client2 = Yahoo()
client2.send_email("Hello!")
Output:
Sending 'Hello!' from Gmail
Sending 'Hello!' from Yahoo
5.5.2 Method Overriding
• Overriding is the ability of a class to change the implementation of a method provided by one of its
base class. Method overriding is thus a strict part of the inheritance mechanism.
• To override a method in the base class, we must define a new method with same name and same
parameters in the derived class.
• Overriding is a very important part of OOP since it is the feature that makes inheritance exploit its
full power. Through method overriding a class may "copy" another class, avoiding duplicated code,
and at the same time enhance or customize part of it.
Example 1: For method overriding.
class A: # parent class
"Parent Class"
def display(self):
print ('This is base class.')
class B(A): #derived class
"Child/Derived class"
def display(self):
print ('This is derived class.')
obj = B() # instance of child
obj.display() # child calls overridden method
Output:
This is derived class.
• In Inheritance delegation occurs automatically, but if a method is overridden the implementation of
the parent is not considered at all. So, if you want to run the implementation of one or more of the
ancestors of your class, you have to call them explicitly.
Using super() Method:
• The super() method gives you access to methods in a superclass from the subclass that inherits from
it.
• The super() method also returns a temporary object of the superclass that then allows you to call that
superclass’s methods.
Example 2: For overriding with super().
class A: # parent class
"Parent Class"
def display(self):
print ('This is base class.')
class B(A): # derived class
"Child/Derived class"
def display(self):
super().display()
print ('This is derived class.')
obj = B() # instance of child
obj.display() # child calls overridden method
Output:
This is base class.
This is derived class.
Programming with 'Python' 5.15 Object Oriented Programming in Python
Objects Program
class S2:
Class
class X(S1, S2):
def attr(self,....):
self.attr = V
Instance
object = x()
object.attr?
Fig. 5.6
• Fig. 5.6 summarizes the way namespace trees are constructed and populated with names. Generally:
1. Instance attributes are generated by assignments to self attributes in methods.
2. Class attributes are created by statements (assignments) in class statements.
3. Superclass links are made by listing classes in parentheses in a class statement header.
• The net result is a tree of attribute namespaces that leads from an instance, to the class it was
generated from, to all the superclasses listed in the class header.
• Python searches upward in this tree, from instances to superclasses, each time we use qualification
to fetch an attribute name from an instance object.
Specializing Inherited Methods:
• The tree-searching model of inheritance just described turns out to be a great way to specialize
systems. Because inheritance finds names in derived classes before it checks base classes, derived
classes can replace default behavior by redefining their base classes’ attributes.
• In fact, we can build entire systems as hierarchies of classes, which are extended by adding new
external derived classes rather than changing existing logic in-place. The idea of redefining
inherited names leads to a variety of specialization techniques.
• For instance, derived classes may replace inherited attributes completely, provide attributes that a
base class expects to find, and extend base class methods by calling back to the base class from an
overridden method. Here is an example that shows how extension works.
Example : For specialized inherited methods.
class A: # parent class
"Parent Class"
def display(self):
print ('This is base class.')
Programming with 'Python' 5.17 Object Oriented Programming in Python
Output:
Inheritor...
in Super.method
Replacer...
in Replacer.method
Extender...
in Super.method
in Extender.method
Provider...
in Provider.action
• At the end of this program instances of three different classes are created in a for loop. Because
classes are objects, you can put them in a tuple and create instances generically.
• Classes also have the special _ _name_ _ attribute, which preset to a string containing the name in
the class header.
• In previous example, when we call the delegate method through a provider instance, two
independent inheritance searches occur:
1. On the initial x.delegate call, Python finds the delegate method in Super by searching the
Provider instance and above. The instance x is passed into the method’s self argument as usual.
2. Inside the Super.delegate method, self.action invokes a new, independent inheritance search of
self and above. Because self references a Provider instance, the action method is located in the
Provider subclass.
• The superclass in this example is what is sometimes called an abstract superclass − a class that
expects parts of its behavior to be provided by its subclasses.
Practice Questions
1. What is OOP?
2. List the features and explain about different Object Oriented features supported by Python.
3. List and explain built in class attributes with example.
4. Design a class that store the information of student and display the same.
5. What are basic overloading methods?
6. What is method overriding? Write an example.
7. Explain class inheritance in Python with an example.
8. How to declare a constructor method in python? Explain.
9. How operator overloading can be implemented in Python? Give an example.
10. Write a Python program to implement the concept of inheritance.
11. Create a class employee with data members: name, department and salary. Create suitable
methods for reading and printing employee information.
12. What is data abstraction? Explain in detail.
13. Define the following terms:
(i) Object
(ii) Class
(iii) Inheritance
(iv) Data abstraction.
14. Describe the term composition classes with example.
15. Explain customization via inheritance specializing inherited methods.
6…
File I/O Handling and
Exception Handling
Chapter Outcomes…
▣ Write Python code for the given reading values from keyboard.
▣ Read data from the given file.
▣ Write the given data to a file.
▣ Handle the given exceptions through Python program.
Learning Objectives…
[
6.0 INTRODUCTION
• A file is a collection of related data that acts as a container of storage as data permanently. The file
processing refers to a process in which a program processes and accesses data stored in files.
• A file is a computer resource used for recording data in a computer storage device. The processing on
a file is performed using read/write operations performed by programs.
• Python supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files.
• Python programming provides modules with functions that enable us to manipulate text files and
binary files. Python allows us to create files, update their contents and also delete files.
• A text file is a file that stores information in the term of a sequence of characters (textual
information), while a binary file stores data in the form of bits (0s and 1s) and used to store
information in the form of text, images, audios, videos etc.
6.1 I/O OPERATIONS (READING KEYBOARD INPUT, PRINTING TO SCREEN)
• In any programming language an interface plays a very important role. It takes data from the user
(input) and displays the output.
• One of the essential operations performed in Python language is to provide input values to the
program and output the data produced by the program to a standard output device (monitor).
• The output generated is always dependent on the input values that have been provided to the
program. The input can be provided to the program statically and dynamically.
[6.1]
Programming with 'Python' 6.2 File I/O Handling and Exception Handling
• In static input, the raw data does not change in every run of the program. While in dynamic input,
the raw data has a tendency to change in every run of the program.
• Python language has predefined functions for reading input and displaying output on the screen,
Input can also be provided directly in the program by assigning the values to the variables. Python
language provides numerous built in functions that are readily available to us at Python prompt.
• Some of the functions like input() and print() are widely used for standard Input and Output (I/O)
operations, respectively.
1. Output (Printing to Screen):
• The function print() is used to output data to the standard output devices i.e., monitor/screen. The
output can redirect or store on to a file also.
• The message can be a string, or any other object, the object will be converted into a string before
written to the screen.
Syntax: print(object(s), separator=separator, end=end, file=file, flush=flush)
Parameter Values:
(i) object(s): It can be any object but will be converted to string before printed.
(ii) sep='separator': Optional. Specify how to separate the objects, if there is more than one. Default
is ' '.
(iii) end='end': Optional. Specify what to print at the end. Default is '\n' (line feed).
(iv) file: Optional. An object with a write method. Default is sys.stdout.
(v) flush: Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default
is False.
Example: For output using print().
>>> print("Hello", "how are you?", sep=" ---")
Hello ---how are you?
>>> print(10,20,30,sep='-')
10-20-30
• To make the output more attractive formatting is used. This can be done by using the str.format()
method.
Example: For output using format().
>>> a=10
>>> b=20
>>> print('Value of a is {} and b is {}'.format(a,b))
Value of a is 10 and b is 20
>>> print('I will visit {0} and {1} in summer'.format('Jammu','Kashmir')
I will visit Jammu and Kashmir in summer
>>>
• Just like old sprint() style used in C programming language, we can format the output in Python
language also. The % operator is used to accomplish this.
Example: For output with %.
>>> x=12.3456789
>>> print('The value of x=%3.2f'%x)
The value of x=12.35
>>> print('The value of x=%3.4f'%x)
The value of x=12.3457
Programming with 'Python' 6.3 File I/O Handling and Exception Handling
5
>>> type(x)
<class 'int'>
>>> x=float(input())
2.5
>>> type(x)
<class 'float'>
6.2 FILES
• File is a named location on disk to store related information. It is used to permanently store data in a
non-volatile memory, (e.g. hard disk).
• Since, Random Access Memory (RAM) is volatile which loses its data when computer is turned OFF,
we use files for future use of the data.
• Files are divided into following two categories:
1. Text Files: Text files are simple texts in human readable format. A text file is structured as
sequence of lines of text.
2. BinaryFiles: Binary files have binary data (0s and 1s) which is understood by the computer.
• When we want to read from or write to a file we need to open it first. When we are done, it needs to
be closed, so that resources that are tied with the file are freed.
• Hence, in Python a file operation takes place in the following order:
o Open a file.
o Read or write (perform operation).
o Close the file.
6.2.1 Opening File in different Modes
• All files in Python programming are required to be open before some operation (read or write) can be
performed on the file. In Python programming while opening a file, file object is created, and by
using this file object we can perform different set as operations on the opened file.
• Python has a built-in function open() to open a file. This function returns a file object also called a
handle, as it is used to read or modify the file accordingly.
Syntax: file object = open(file_name [, access_mode][, buffering])
Parameters:
file_name: The file_name argument is a string value that contains the name of the file that we want
to access.
access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read,
write, append, etc. This is optional parameter and the default file access mode is read (r).
buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line
buffering is performed while accessing a file. If we specify the buffering value as an integer greater
than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size
is the system default (default behavior).
• If the path is in current working directory, we can just provide the filename, just like in the following
examples:
>>> file=open("sample.txt")
>>> file.read()
'Hello I am there\n' # content of file
>>>
Programming with 'Python' 6.5 File I/O Handling and Exception Handling
• If still we are getting “no such file or directory” error then use following command to confirm the
proper file name and extension on current working directory (PWD).
>>> import os
>>> os.listdir() # display file and folder of current working directory
['DLLs', 'Doc', 'etc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mypkg', 'NEWS.txt',
'p1.py', 'p2.py', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe',
'sample.txt', 'Scripts', 'share', 'tcl', 'test.py', 'Tools', 'vcruntime140.dll',
'_ _pycache_ _']
>>>
• If the file resides in a directory other than PWD, we have to provide the full path with the file name:
>>> file=open("D:\\files\\sample.txt")
>>> file.read()
'Hello I am there\n'
>>>
• We can specify the mode while opening a file. In mode, we specify whether we want to read 'r',
write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary
mode.
• The default is reading in text mode. In this mode, we get strings when reading from the file. The
binary mode returns bytes and this is the mode to be used when dealing with non-text files like
image or exe files.
• The mode of the file specifies the possible operations that can be performed on the file i.e., what
purpose we are opening a file.
6.2.2 Different Modes of Opening File
• Like, C, C++, and Java, a file in Python programming can be opened in various modes depending
upon the purpose. For that, the programmer needs to specify the mode whether read 'r', write 'w', or
append 'a' mode.
• Apart from this, two other modes exist, which specify to open the file in text mode or binary mode.
1. The text mode returns strings while reading from the file. The default is reading in text mode.
2. The binary mode returns bytes and this is the mode to be used when dealing with non-text files
like image or executable files.
• The text and binary modes are used in conjunction with the r, w, and a modes. The list of all the
modes used in Python are given in following table:
Sr. No. Mode Description
1. r Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
2. rb Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
3. r+ Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.
4. rb+ Opens a file for both reading and writing in binary format. The file pointer placed
at the beginning of the file.
5. w Opens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.
6. wb Opens a file for writing only in binary format. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
7. w+ Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
contd. …
Programming with 'Python' 6.6 File I/O Handling and Exception Handling
8. wb+ Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for reading
and writing.
9. a Opens a file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.
10. ab Opens a file for appending in binary format. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
11. a+ Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
12. ab+ Opens a file for both appending and reading in binary format. The file pointer is at
the end of the file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading and writing.
13. t Opens in text mode (default).
14. b Opens in binary mode.
15. + Opens a file for updating (reading and writing).
Example: For different modes of opening a file.
f = open("test.txt") # opening in r mode (reading only)
f = open("test.txt",'w') # opens in w mode (writing mode)
f = open("img.bmp",'rb+') # read and write in binary mode
Output:
sample.txt
r
cp1252
True
Output:
**content of file1**
Hello,I am There
**content of file1**
first line
second line
third line
2. writelines(list) Method:
• It writes a sequence of strings to the file. The sequence can be any iterable object producing strings,
typically a list of strings. There is no return value.
Example: For writelines() method.
fruits=["Orange\n","Banana\n","Apple\n"]
f=open("sample.txt",mode="w+",encoding="utf-8")
f.writelines(fruits)
f.close()
f=open("sample.txt","r")
print(f.read())
Output:
Orange
Banana
Apple
second line
third line
2. readline([n]) Method:
• The readline() method just output the entire line whereas readline(n) outputs at most n bytes of a
single line of a file. It does not read more than one line. Once, the end of file is reached, we get empty
string on further reading.
Programming with 'Python' 6.9 File I/O Handling and Exception Handling
Example 2:
fruits=["Orange\n","Banana\n","Apple\n"]
f=open("sample.txt",mode="w+",encoding="utf-8")
for fru in fruits:
f.write(fru)
print("Tell the byte at which the file cursor is:",f.tell())
f.seek(0)
for line in f:
print(line)
Output:
Tell the byte at which the file cursor is: 23
Orange
Banana
Apple
File Related Standard Functions:
Sr.
Function Description Example
No.
1. file.close() Close the file. We need to reopen it f.close()
for further access.
2. file.flush() Flush the internal buffer. f.flush()
print(f.read())
f.close()
3. file.fileno() Returns an integer file descriptor. print(f.fileno())
f.close()
4. file.isatty() It returns true if file has a <tty> print(f.isatty())
attached to it. f.close()
6. file.read() This function reads the entire file and lines =f.read()
returns a string. f.write(lines)
f.close()
10. file.readlines() Reads the content of a file line by line lines =f.readlines()
and returns them as a list of strings. f.writelines(lines)
f.close()
11. file.readlines(size_hint) It calls the readline() to read until text =f.readlines(25)
EOF. It returns a list of lines read print(text)
from the file. If you pass <size_hint>, f.close()
then it reads lines equalling the
<size_hint> bytes.
12. file.seek(offset[, from]) Sets the file’s current position. position =f.seek(0,0);
print(position)
f.close()
13. file.tell() Returns the file’s current position. lines =f.read(10)
#tell()
print(f.tell())
f.close()
14. file.truncate(size) Truncates the file’s size. If the f.truncate(10)
optional size argument is present, the f.close()
file is truncated to (at most) that size.
15. file.write(string) It writes a string to the file. And it line ='Welcome Geeks\n'
doesn’t return any value. f.write(line)
f.close()
16. file.writelines(sequence) Writes a sequence of strings to the lines =f.readlines()
file. The sequence is possibly an #writelines()
iterable object producing strings, f.writelines(lines)
typically a list of strings.
f.close()
Sr.
Function Description Example
No.
1. os.getcwd() Show current working import os
directory. os.getcwd()
7. os.rename(current,new) os.rename("sample.txt","sample1.txt
Rename a file.
")
6.2.10 Directories
• If there are a large number of files to handle in the Python program, we can arrange the code within
different directories to make things more manageable.
• A directory or folder is a collection of files and sub directories. Python has the os module, which
provides us with many useful methods to work with directories (and files as well).
6.2.10.1 Create New Directory
• We can make a new directory using the mkdir() method.
• This method takes in the path of the new directory. If the full path is not specified, the new directory
is created in the current working directory.
Syntax: os.mkdir(“newdir”)
Example:
>>> import os
>>> os.mkdir("testdir")
sent1 = input();
c.write(sent1);
c.close();
print("\nContent successfully placed inside the file.!!");
Output:
Enter 'x' for exit.
Enter file name to create and write content: file1
Output:
Enter file name: file1
Enter letter to be searched:o
Occurrences of the letter:
7
6.3.1 Introduction
• An exception is also called as runtime error that can halt the execution of the program.
• An exception is an error that happens/occurs during execution of a program. When that error
occurs, Python generate an exception that can be handled, which avoids the normal flow of the
program's instructions.
• Errors detected during execution are called exceptions. An exception is an event (usually an error),
which occurs during the execution of a program that disrupts the normal flow of execution of the
program (or program's instructions).
• In Python programming we can handle exceptions using try-except statement, try-finally
statement and raise statement.
Programming with 'Python' 6.18 File I/O Handling and Exception Handling
• Following table lists all the standard exceptions available in Python programming language:
Sr. No. Exception Cause of Error
1. ArithmeticError Base class for all errors that occur for numeric calculation.
2. AssertionError Raised in case of failure of the assert statement.
3. AttributeError Raised in case of failure of attribute reference or assignment.
4. Exception Base class for all exceptions.
5. EOFError Raised when there is no input from either the raw_input() or
input() function and the end of file is reached.
6. EnvironmentError Base class for all exceptions that occur outside the Python
environment.
7. FloatingPointError Raised when a floating point calculation fails.
8. ImportError Raised when an import statement fails.
9. IndexError Raised when an index is not found in a sequence.
10. IOError Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that
does not exist.
11. IndentationError Raised when indentation is not specified properly.
12. KeyboardInterrupt Raised when the user interrupts program execution, usually by
pressing Ctrl+c.
13. KeyError Raised when the specified key is not found in the dictionary.
14. LookupError Base class for all lookup errors.
15. NameError Raised when an identifier is not found in the local or global
namespace.
16. NotImplementedError Raised when an abstract method that needs to be implemented in
an inherited class is not actually implemented.
17. OverflowError Raised when a calculation exceeds maximum limit for a numeric
type.
18. OSError Raised for operating system-related errors.
19. RuntimeError Raised when a generated error does not fall into any category.
20. StopIteration Raised when the next() method of an iterator does not point to any
object.
21. SystemExit Raised by the sys.exit() function.
22. StandardError Base class for all built-in exceptions except StopIteration and
SystemExit.
23. SyntaxError Raised when there is an error in Python syntax.
24. SystemError Raised when the interpreter finds an internal problem, but when
this error is encountered the Python interpreter does not exit.
25. SystemExit Raised when Python interpreter is quit by using the sys.exit()
function. If not handled in the code, causes the interpreter to exit.
26. TypeError Raised when an operation or function is attempted that is invalid
for the specified data type.
27. UnboundLocalError Raised when trying to access a local variable in a function or
method but no value has been assigned to it.
28. ValueError Raised when the built-in function for a data type has the valid type
of arguments, but the arguments have invalid values specified.
29. ZeroDivisionError Raised when division or modulo by zero takes place for all numeric
types.
Programming with 'Python' 6.19 File I/O Handling and Exception Handling
Output:
Enter an integer: b
Error Occurred
Please enter valid value
Enter an integer: 0
Error Occurred
Please enter valid value
Enter an integer: 5
Division is: 2.0
6.3.2.3 try…finally
• The try statement in Python can have an optional finally clause. This clause is executed always and is
generally used to release external resources.
• The statement written in finally clause will always be executed by the interpreter, whether the try
statement raises an exception or not.
• A finally block is always executed before leaving the try statement, whether an exception is occurred
or not. When an exception is occurred in try block and has not been handled by an except block, it is
re-raised after the finally block has been executed.
• The finally clause is also executed “on the way out” when any other clause of the try statement is left
via a break, continue or return statement.
Syntax:
try:
certain operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Example: For try-finally.
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("file is closing")
fh.close()
Example: Program to check for ZeroDivisionError Exception.
x=int(input("Enter first value:"))
y=int(input("Enter second value:"))
try:
result=x/y
except ZeroDivisionError:
print("Division by Zero")
else:
print("Result is:",result)
finally:
print("Execute finally clause")
Programming with 'Python' 6.22 File I/O Handling and Exception Handling
Output 1:
Enter first value:5
Enter second value:0
Division by Zero
Execute finally clause
Output 2:
Enter first value:10
Enter second value:5
Result is: 2.0
Execute finally clause
class AgeSmallException(Error):
"""Raised when the input value is too small""" # empty class
pass
# main program
while True:
try:
age = int(input("Enter your age for election: "))
if age < 18:
raise AgeSmallException
else:
print("you are eligible for election")
break
except AgeSmallException:
print("This value is too small, try again!")
print()
Output:
Enter your age for election: 11
This value is too small, try again!
Enter your age for election: 15
This value is too small, try again!
Enter your age for election: 18
you are eligible for election
Example 2: Raise a user defined exception id password is incorrect.
class InvalidPassword(Exception):
pass
def verify_password(pswd):
if str(pswd) != "abc":
raise InvalidPassword
else:
print('Valid Password: '+str(pswd))
# main program
verify_password("abc") # won't raise exception
verify_password("xyz") # will raise exception
Output:
Valid Password: abc
Traceback (most recent call last):
File "C:\Users\Meenakshi\AppData\Local\Programs\Python\Python37\p1.py", line 12, in
<module>
verify_password("xyz") # will raise exception
File "C:\Users\Meenakshi\AppData\Local\Programs\Python\Python37\p1.py", line 6, in
verify_password
raise InvalidPassword
InvalidPassword
Programming with 'Python' 6.24 File I/O Handling and Exception Handling
Practice Questions
1. What is file? Enlist types of files in Python programming.
2. What is exception?
3. Explain the term exception handling in detail.
4. Explain different modes of opening a file.
5. Write the syntax of fopen() with example.
6. What are various modes of file object? Explain any five as them.
7. Explain exception handling with example using try, except, raise keywords.
8. Explain try…except blocks for exception handling in Python.
9. Explain various built in functions and methods.
10. Explain open() and close() methods for opening and closing a file.
11. Explain any three methods associated with files in Python.
12. List and explain any five exceptions in Python.
13. List out keywords used in exception handling.
14. How python handles the exception? Explain with an example program.
15. Differentiate between an error and exception.
16. How to create a user defined exception?
17. Give the syntax and significance of input() method.
18. Give syntax of the methods which can be used to take input from the user in Python program.
19. Write a Python program which will throw exception if the value entered by user is less than zero.
20. Write a Python program to accept an integer number and use try/except to catch the exception if
a floating point number is entered.
21. Write a Python program to read contents of first.txt file and write same content in second.txt file
22. Write a Python program to append data to an existing file ‘python.py’. Read data to be appended
from the use. Then display the contents of entire file.
23. Write a Python program to read a text file and print number of lines, words and characters.
24. Describe the term file I/O handling in detail.
Programs
1. Program to convert U.S. dollars to Indian rupees.
dollars = float(input("Please enter dollars:"))
rupees = dollars * 70
print("Dollars: ",dollars)
print("Rupees: ",rupees)
Output:
Please enter dollars:50
Dollars: 50.0
Rupees: 3500.0
2. Program to convert bits to Megabytes, Gigabytes and Terabytes.
b=float(input("Enter Number of Bytes: "))
kb=b/1024
mb=b/(1024*1024)
gb=b/(1024*1024*1024)
tb=b/(1024*1024*1024*1024)
print("Bytes=",b,"Kilobyte=",kb)
print("Bytes=",b,"Megabyte=",mb)
print("Bytes=",b,"Gigabyte=",gb)
print("Bytes=",b,"Terabyte=",tb)
Output:
Enter Number of Bytes: 50
Bytes= 50.0 Kilobyte= 0.048828125
Bytes= 50.0 Megabyte= 4.76837158203125e-05
Bytes= 50.0 Gigabyte= 4.6566128730773926e-08
Bytes= 50.0 Terabyte= 4.547473508864641e-11
3. Program to check if a number is positive, negative or zero.
number=int(input("Enter any number: "))
if(number<0):
print(number, " is negative number")
elif (number>0):
print(number," is positive nnumber")
else:
print(number," is zero")
Output:
Enter any number: -10
-10 is negative number
4. Print the following patterns using loop:
*
***
*****
***
*
for i in range(3):
print(' '*(3-i-1) + '*'*(2*i+1))
for j in reversed(range(2)):
print(' '*(2-j) + '*'*(2*j+1))
[P.1]
Programming with 'Python' P.2 Programs
Output:
*
***
*****
***
*
5. Print the following patterns using loop
1010101
10101
101
1
i=3
j=0
k=0
while(i>=0):
a=" "*k+"10"*i+"1"+" "*j
print(a)
i=i-1
j=j+2
k=k+1
if(i<0 and j>=4):
break
Output:
1010101
10101
101
1
6. Python program to find the sum of first 10 natural numbers using for loop.
sum=0
for i in range(0,10):
print(i)
sum=sum+i
print("Sum of numbers= ",sum)
Output:
0
1
2
3
4
5
6
7
8
9
Sum of numbers= 45
7. Python program to sum and multiplication of all the items in a list.
sum=0
mul=1
list1 = [2,3,4,5,6]
for ele in range(0, len(list1)):
sum = sum +list1[ele]
mul = mul*list1[ele]
print("Sum of all elements in given list: ", sum)
print("Multiplication of all elements in given list: ", mul)
Output:
Sum of all elements in given list: 20
Multiplication of all elements in given list: 720
Programming with 'Python' P.3 Programs
8. Python program to get the largest number,smallest number and reverse the list.
list1 = [12, 3, 48, 10, 36]
print("Smallest Number in list: ",min(list1))
print("Largest Number in list: ",max(list1))
list1.reverse()
print("Reverse list: ",list1)
Output:
Smallest Number in list: 3
Largest Number in list: 48
Reverse list: [36, 10, 48, 3, 12]
9. Python program to find common items from two lists.
list1 = [10,"Green",20,"Red"]
list2 = [30, "Green", 10, "Pink"]
print(set(list1) & set(list2))
Output:
{10, 'Green'}
10. Python program to select the even items of a list.
list1 = [12, 3, 48, 10, 36]
even=[]
odd=[]
for j in list1:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)
Output:
The even list [12, 48, 10, 36]
The odd list [3]
11. Create a tuple and find the minimum and maximum number from it.
tup1=(11,2,3)
print("maximum element of tuple:", max(tup1))
print("minimum element of tuple:", min(tup1))
Output:
maximum element of tuple: 11
minimum element of tuple: 2
12. Python program to find the repeated items of a tuple.
tupl = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(tupl)
count = tupl.count(4)
print(count)
Output:
(2, 4, 5, 6, 2, 3, 4, 4, 7)
3
13. Print the number in words for example: 1234 => One Two Three Four.
ones = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight',
'Nine']
num=input("enter a number")
print(num)
word=[]
for a in num:
word.append(ones[int(a)])
print (word)
Output:
enter a number1234
1234
['One', 'Two', 'Three', 'Four']
Programming with 'Python' P.4 Programs
14. Python program to create a set, add member(s) in a set and remove one item from set.
set1= {0, 2, 4, 6, 8}
set1.add(10)
set1.add(12)
print("After Addition", set1)
set1.remove(0)
print("After Deletion",set1)
Output:
After Addition {0, 2, 4, 6, 8, 10, 12}
After Deletion {2, 4, 6, 8, 10, 12}
15. Python program to perform following operations on set: intersection of sets, union of sets, set
difference, symmetric difference, clear a set.
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
print("Union :", A | B)
print("Intersection :", A & B)
print("Difference :", A - B)
print("Symmetric difference :", A ^ B)
Output:
Union : {0, 1, 2, 3, 4, 5, 6, 8}
Intersection : {2, 4}
Difference : {0, 8, 6}
Symmetric difference : {0, 1, 3, 5, 6, 8}
16. Python program to find maximum and the minimum value and length of set.
set1= {0, 2, 4, 6, 8}
print("Maximum value in set", max(set1))
print("minimum value in set",min(set1))
print("length of set",len(set1))
Output:
Maximum value in set 8
minimum value in set 0
length of set 5
17. Python script to sort (ascending and descending) a dictionary by value.
import operator
d = {1:"One", 2:"Two", 3:"Three", 4:"Four", 0:"zero"}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True)
print('Dictionary in descending order by value : ',sorted_d)
Output:
Original dictionary : {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 0: 'zero'}
Dictionary in ascending order by value : [(0, 'zero'), (1, 'One'), (2, 'Two'), (3,
'Three'), (4, 'Four')]
Dictionary in descending order by value : [(4, 'Four'), (3, 'Three'), (2, 'Two'),
(1, 'One'), (0, 'zero')]
18. Python script to concatenate following dictionaries to create a new one.
Sample Dictionary:
dic1 = {1:10, 2:20}
dic2 = {3:30, 4:40}
dic3 = {5:50,6:60}
dic1={1:10, 2:20}
dic2={3:30, 4:40}
Programming with 'Python' P.5 Programs
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3):
dic4.update(d)
print(dic4)
Output:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
19. Python program to combine two dictionary adding values for common keys.
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
from collections import Counter
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d = Counter(d1) + Counter(d2)
print(d)
Output:
Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})
20. Python program to print all unique values in a dictionary.
Sample Data: [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"}, {"V":"S009"}, {"VIII":"S007"}]
L = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"},
{"V":"S009"},{"VIII":"S007"}]
print("Original List: ",L)
u_value = set(val for dic in L for val in dic.values())
print("Unique Values: ",u_value)
Output:
Original List: [{'V': 'S001'}, {'V': 'S002'}, {'VI': 'S001'}, {'VI': 'S005'},
{'VII': 'S005'}, {'V': 'S009'}, {'VIII': 'S007'}]
Unique Values: {'S001', 'S007', 'S005', 'S002', 'S009'}
21. Python program to find the highest 3 values in a dictionary.
from heapq import nlargest
dict1 = {'a':500, 'b':600, 'c': 560,'d':400, 'e':800, 'f': 20}
largest3 = nlargest(3, dict1, key=dict1.get)
print(largest3)
Output:
['e', 'b', 'c']
22. Python function that accepts a string and calculate the number of upper case letters and lower
case letters.
def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}
for c in s:
if c.isupper():
d["UPPER_CASE"]+=1
elif c.islower():
d["LOWER_CASE"]+=1
else:
pass
print ("Original String : ", s)
print ("No. of Upper case characters : ", d["UPPER_CASE"])
print ("No. of Lower case Characters : ", d["LOWER_CASE"])
23. Python program to generate a random float where the value is between 5 and 50 using Python
math module.
import random
print("Random float number between given range is ", random.uniform(5,50))
Output:
Random float number between given range is 22.00227692464644
24. Python function that takes a number as a parameter and check the number is prime or not.
def prime(n):
for i in range(2,n+1):
ifn%i==0:
break
if i==n:
print(n," is prime number")
else:
print(n," is not a prime number")
n1=int(input("Enter a number:"))
prime(n1)
Output:
Enter a number:6
6 is not a prime number
25. Python function to calculate the factorial of a number (a non-negative integer). The function
accepts the number as an argument.
def fact(num):
fact=1
if num< 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
fact=fact*i
print("The factorial of ",num," is ",fact)
n1=int(input("Enter a number:"))
fact(n1)
Output:
Enter a number:5
The factorial of 5 is 120
26. Python program that will calculate area and circumference of circle using inbuilt Math module.
import math
r = float(input('Enter the radius of the circle :'))
area = math.pi * r * r
circum=2 * math.pi * r
print("Area of the circle is : %.2f" %area)
print("Circumference of the circle is : %.2f" %circum)
Output:
Enter the radius of the circle :6
Area of the circle is : 113.10
Circumference of the circle is : 37.70
27. Python program that will display Calendar of given month using calendar module.
import calendar
yy = 2020
mm = 1
print(calendar.month(yy, mm))
Programming with 'Python' P.7 Programs
Output:
January 2020
Mo Tu We ThFrSa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
28. Python program to create two matrices and perform addition, subtraction, multiplication and
division operation on matrix.
import numpy
x = numpy.array([[1, 2], [4, 5]])
y = numpy.array([[7, 8], [9, 10]])
print ("The element wise addition of matrix is : ")
print (numpy.add(x,y))
print ("The element wise subtraction of matrix is : ")
print (numpy.subtract(x,y))
print ("The element wise division of matrix is : ")
print (numpy.divide(x,y))
print ("The element wise multiplication of matrix is : ")
print (numpy.multiply(x,y))
print ("The product of matrices is : ")
print (numpy.dot(x,y))
Output:
The element wise addition of matrix is :
[[ 8 10]
[13 15]]
The element wise subtraction of matrix is :
[[-6 -6]
[-5 -5]]
The element wise division of matrix is :
[[0.14285714 0.25 ]
[0.44444444 0.5 ]]
The element wise multiplication of matrix is :
[[ 7 16]
[36 50]]
The product of matrices is :
[[25 28]
[73 82]]
29. NumPy program to generate six random integers between 10 and 30.
import numpy as np
x = np.random.randint(low=10, high=30, size=6)
print(x)
Output:
[27 19 26 28 26 12]
30. Python program to create a class to print an integer and a character with two methods having
the same name but different sequence of the integer and the character parameters. For example,
if the parameters of the first method are of the form (int n, char c), then that of the second
method will be of the form (char c, int n)
class Display:
def printmsg(self, x, y):
if type(x)== int:
print("Integer Message=" ,x);
Programming with 'Python' P.8 Programs
else:
print("Character Message=" ,x);
a=Display();
a.printmsg(20,'Meenakshi')
a.printmsg('Meenakshi',20)
Output:
Integer Message= 20
Character Message= Meenakshi
31. Python program to create a class to print the area of a square and a rectangle. The class has two
methods with the same name but different number of parameters. The method for printing area
of rectangle has two parameters which are length and breadth respectively while the other
method for printing area of square has one parameter which is side of square.
class Area:
def print Area(self, x, y=None):
if y is not None:
print("Area of Rectangle=",x*y)
else:
print("Area of Square=",x*x);
a=Area();
a.printArea(10)
a.printArea(10,20)
32. Python program to create a class 'Degree' having a method 'getDegree' that prints "I got a
degree". It has two subclasses namely 'Undergraduate' and 'Postgraduate' each having a method
with the same name that prints "I am an Undergraduate" and "I am a Postgraduate" respectively.
Call the method by creating an object of each of the three classes.
class Degree:
def getDegree(self):
print("I got a diploma degree")
class Undergraduate(Degree):
def getDegree(self):
print("I got a undergraduate degree")
class Postgraduate(Degree):
def getDegree(self):
print("I got a postgradyate degree")
d=Degree()
u=Undergraduate()
p=Postgraduate()
d.getDegree()
u.getDegree()
p.getDegree()
Output:
I got a diploma degree
I got a undergraduate degree
I got a postgradyate degree