0% found this document useful (0 votes)
428 views160 pages

All 5 Units-Python Programming

Python is a high-level, interpreted, interactive and object-oriented scripting language that is designed to be highly readable. It has a simple structure, clearly defined syntax and is easy to learn and maintain. Python can be used for both simple and complex applications like web development, scientific computing, and software development. It supports features like object-oriented programming, exception handling, dynamic typing, very high level dynamic data types and methods, and automatic memory management.

Uploaded by

kookie
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
428 views160 pages

All 5 Units-Python Programming

Python is a high-level, interpreted, interactive and object-oriented scripting language that is designed to be highly readable. It has a simple structure, clearly defined syntax and is easy to learn and maintain. Python can be used for both simple and complex applications like web development, scientific computing, and software development. It supports features like object-oriented programming, exception handling, dynamic typing, very high level dynamic data types and methods, and automatic memory management.

Uploaded by

kookie
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 160

PYTHON PROGRAMMING KG College of Arts and Science

UNIT I
BASICS : Python – Variables – Executing Python from the Command Line – Editing Python
Files – Python Reserved Words – Basic Syntax-Comments – Standard Data Types – Relational
Operators – Logical Operators – Bit Wise Operators – Simple Input and Output.

I. DEFINITION:
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages.
 Python is Interpreted: Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL andPHP.
 Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write yourprograms.
 Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code withinobjects.
 Python is a Beginner's Language: Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers togames.
1.2 HISTORY OF PYTHON
 Python was developed by Guido van Rossum in the late eighties
and early nineties at the National Research Institute for
Mathematics and Computer Science in theNetherlands.
 Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, Unix shell, and other
scriptinglanguages.
 At the time when he began implementing Python, Guido van Rossum was also reading
the published scripts from "Monty Python's Flying Circus" (a BBC comedy series from
the seventies, in the unlikely case you didn't know). It occurred to him that he needed a
name that was short, unique, and slightly mysterious, so he decided to call the language
Python.
 Python is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing itsprogress.
 Python 1.0 was released on 20 February,1991.
 Python 2.0 was released on 16 October 2000 and had many major new features,
including a cycle detecting garbage collector and support for Unicode. With this release
the development process was changed and became more transparent and community-
backed.
 Python 3.0 (which early in its development was commonly referred to as Python 3000 or
py3k), a major, backwards-incompatible release, was released on 3 December 2008 after
a long period of testing. Many of its major features have been back ported to the
backwards-compatible Python 2.6.x and 2.7.x versionseries.
 In January 2017 Google announced work on a Python 2.7 to go transcompiler, which The
Register speculated was in response to Python 2.7's plannedend-of-life.

Page 1
PYTHON PROGRAMMING KG College of Arts and Science

1.3 PYTHON FEATURES:


Python's features include:
 Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the languagequickly.
 Easy-to-read: Python code is more clearly defined and visible to theeyes.
 Easy-to-maintain: Python's source code is fairlyeasy-to-maintain.
 A broad standard library: Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, andMacintosh.
 Interactive Mode: Python has support for an interactive mode which allows interactive
testing and debugging of snippets ofcode.
 Portable: Python can run on a wide variety of hardware platforms and has the same
interface on allplatforms.
 Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be moreefficient.
 Databases: Python provides interfaces to all major commercialdatabases.
 GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries, and windows systems, such as Windows MFC, Macintosh,
and the X Window system ofUNIX.
 Scalable: Python provides a better structure and support for large programs than shell
scripting.

1.4 NEED OF PYTHON PROGRAMMING AND ITS WORKING


 Softwar equality
Python code is designed to be readable, and hence reusable and maintainable—
much more so than traditional scripting languages. The uniformity of Python code makes
it easy to understand, even if you did not write it. In addition, Python has deep support
for more advanced software reuse mechanisms, such as object-oriented (OO) and
functionprogramming.
 Developer productivity
Python boosts developer productivity many times beyond compiled or statically
typed languages such as C, C++, and Java. Python code is typically one-third to less to
debug, and less to maintain after the fact. Python programs also run immediately, without
the lengthy compile and link steps required by some other tools, further boosting
programmer speed. Program portability Most Python programs run unchanged on all
major computer platforms. Porting Python code between Linux and Windows, for
example, is usually just a matter of copying a script‗s code between machines.
 Support libraries
Python comes with a large collection of prebuilt and portable functionality,
known as the standard library. This library supports an array of application-level
programming tasks, from text pattern matching to network scripting. In addition, Python
can be extended with both home grown libraries and a vast collection of third-party
application support software. Python‗s third-party domain offers tools for website
construction, numeric programming, serial port access, game development, and much
more (see ahead for asampling).

Page 2
PYTHON PROGRAMMING KG College of Arts and Science

 Component integration
Python scripts can easily communicate with other parts of an application, using a
variety of integration mechanisms. Such integrations allow Python to be used as a
product customization and extension tool. Today, Python code can invoke C and C++
libraries, can be called from C and C++ programs, can integrate with Java and .NET
components, can communicate over frameworks such as COM and Silverlight, can
interface with devices over serial ports, and can interact over networks with interfaces
like SOAP, XML-RPC, and CORBA. It is not a standalonetool.
 Enjoyment
Because of Python‗s ease of use and built-in toolset, it can make the act of
programming more pleasure than chore. Although this may be an intangible benefit, its
effect on productivity is an important asset. Of these factors, the first two (quality and
productivity) are probably the most compelling benefits to most Python users, and merit
a fullerdescription.
 It's Object-Oriented
Python is an object-oriented language, from the ground up. Its class model
supports advanced notions such as polymorphism, operator overloading, and multiple
inheritance; yet in the context of Python's dynamic typing, object-oriented programming
(OOP) is remarkably easy to apply. Python's OOP nature makes it ideal as a scripting
tool for object-oriented systems languages such as C++ and Java. For example, Python
programs can subclass (specialized) classes implemented in C++ orJava.
 It's Free
Python is freeware—something which has lately been come to be called open
source software. As with Tcl and Perl, you can get the entire system for free over the
Internet. There are no restrictions on copying it, embedding it in your systems, or
shipping it with your products. In fact, you can even sell Python, if you're so inclined.
But don't get the wrong idea: "free" doesn't mean "unsupported". On the contrary, the
Python online community responds to user queries with a speed that most commercial
software vendors would do well tonotice.
 It's Portable
Python is written in portable ANSI C, and compiles and runs on virtually every
major platform in use today. For example, it runs on UNIX systems, Linux, MS-DOS,
MS-Windows (95, 98, NT), Macintosh, Amiga, Be-OS, OS/2, VMS, QNX, and more.
Further, Python programs are automatically compiled to portable bytecode, which runs
the same on any platform with a compatible version of Python installed (more on this in
the section "It's easy to use"). What that means is that Python programs that use the core
language run the same on UNIX, MS-Windows, and any other system with a Python
interpreter.
 It's Powerful
From a features perspective, Python is something of a hybrid. Its tool set places it
between traditional scripting languages (such as Tcl, Scheme, and Perl), and systems
languages (such as C, C++, and Java). Python provides all the simplicity and ease of use
of a scripting language, along with more advanced programming tools typically found in
systems development languages.
Page 3
PYTHON PROGRAMMING KG College of Arts and Science

 Automatic memory management


Python automatically allocates and reclaims ("garbage collects") objects when no
longer used, and most grow and shrink on demand; Python, not you, keeps track of low-
level memory details.
 Programming-in-the-largesupport
Finally, for building larger systems, Python includes tools such as modules,
classes, and exceptions; they allow you to organize systems into components, do OOP,
and handle events gracefully.
 It's Mixable
Python programs can be easily "glued" to components written in other languages.
In technical terms, by employing the Python/C integration APIs, Python programs can be
both extended by (called to) components written in C or C++, and embedded in (called
by) C or C++ programs. That means you can add functionality to the Python system as
needed and use Python programs within other environments or systems.
 It's Easy toUse
For many, Python's combination of rapid turnaround and language simplicity
make programming more fun than work. To run a Python program, you simply type it
and run it. There are no intermediate compile and link steps (as when using languages
such as C or C++). As with other interpreted languages, Python executes programs
immediately, which makes for both an interactive programming experience and rapid
turnaround after program changes. Strictly speaking, Python programs are compiled
(translated) to an intermediate form called bytecode, which is then run by theinterpreter.
 It's Easy toLearn
This brings us to the topic of this book: compared to other programming
languages, the core Python language is amazingly easy to learn. In fact In fact, you can
expect to be coding significant Python programs in a matter of days (and perhaps in just
hours, if you're already an experienced programmer).
 Internet Scripting
Python comes with standard Internet utility modules that allow Python programs
to communicate over sockets, extract form information sent to a server-side CGI script,
parse HTML, transfer files by FTP, process XML files, and much more. There are also a
number of peripheral tools for doing Internet programming in Python. For instance, the
HTMLGen and pythondoc systems generate HTML files from Python class-based
descriptions, and the JPython system mentioned above provides for seamless
Python/Javaintegration.
 Database Programming
Python's standard pickle module provides a simple object-persistence system: it
allows programs to easily save and restore entire Python objects to files. For more
traditional database demands, there are Python interfaces to Sybase, Oracle, Informix,
ODBC, and more. There is even a portable SQL database API for Python that runs the
same on a variety of underlying database systems, and a system named gadfly that
implements an SQL database for Python programs.

Page 4
PYTHON PROGRAMMING KG College of Arts and Science

 Image Processing, AI, Distributed Objects,Etc.


Python is commonly applied in more domains than can be mentioned here. But in
general, many are just instances of Python's component integration role in action. By
adding Python as a frontend to libraries of components written in a compiled language
such as C, Python becomes useful for scripting in a variety of domains. For instance,
image processing for Python is implemented as a set of library components implemented
in a compiled language such as C, along with a Python frontend layer on top used to
configure and launch the compiled components.

Who Uses Python Today?


1. Google makes extensive use of Python in its web searchsystems.
2. The popular YouTube video sharing service is largely written inPython.
3. The Dropbox storage service codes both its server and desktop client software primarily
inPython.
4. The Raspberry Pi single-board computer promotes Python as its educationallanguage.
5. The widespread BitTorrent peer-to-peer file sharing system began its life as a Python
program.
6. Google‗s App Engine web development framework uses Python as an application
language.
7. Maya, a powerful integrated 3D modeling and animation system, provides a Python
scriptingAPI.
8. Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware
testing.
9. NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific programming
tasks.

1.4.1 How Python Works ?


Byte code Compilation:
Python first compiles your source code (the statements in your file) into a format
known as byte code. Compilation is simply a translation step, and byte code is a lower-
level, platform independent representation of your source code. Roughly, Python translates
each of your source statements into a group of byte code instructions by decomposing them
into individual steps. This byte code translation is performed to speed execution —byte code
can be run much more quickly than the original source code statements in your textfile.

The Python Virtual Machine:

Once your program has been compiled to byte code (or the byte code has been loaded
from existing .pyc file), it is shipped off for execution to something generally known as the
python virtual machine (PVM)

Page 5
PYTHON PROGRAMMING KG College of Arts and Science

1.5 APPLICATIONS OF PYTHON:


1. Systems Programming
2. GUIs
3. InternetScripting
4. ComponentIntegration
5. DatabaseProgramming
6. RapidPrototyping
7. Numeric and ScientificProgramming

1.5.1 What are Python’s Technical Strengths?


1. It‗s Object-Oriented andFunctional
2. It‗s Free
3. It‗s Portable
4. It‗s Powerful
5. It‗s Mixable
6. It‗s Relatively Easy toUse
7. It‗s Relatively Easy toLearn

1.5.2 Download and installation Python software:

Step 1: Go to website www.python.organd click downloads select version which you want.

Step 2: Click on Python 2.7.13 and download. After download open the file.

Page 6
PYTHON PROGRAMMING KG College of Arts and Science

Page 7
PYTHON PROGRAMMING KG College of Arts and Science

Step 3: Click on Next to continue.

Step 4: After installation location will be displayed. The Default location is C:\Python27.
Click on next to continue.

Page 8
PYTHON PROGRAMMING KG College of Arts and Science

Step 5: After the python interpreter and libraries are displayed for installation. Click on Next
to continue.

Step 6: The installation has been processed.

Page 9
PYTHON PROGRAMMING KG College of Arts and Science

Step 7: Click the Finish to complete the installation.

Setting up PATH to python:

 Programs and other executable files can be in many directories, so operatingsystems


provide a search path that lists the directories that the OS searches forexecutables.
 The path is stored in an environment variable, which is a named string maintained by the
operating system. This variable contains information available to the command shell and
other programs.
 Copy the Python installation locationC:\Python27

Page 10
PYTHON PROGRAMMING KG College of Arts and Science

 Right-click the My Computer icon on your desktop and choose Properties. And then
select Advanced Systemproperties.

 Goto Environment Variables and go to System Variables select Path and clickon
Edit.

 Add semicolon (;) at end and copy the location C:\Python27 and give semicolon (;) and
click OK.

Page 11
PYTHON PROGRAMMING KG College of Arts and Science

Running Python:
a. Running PythonInterpreter:
Python comes with an interactive interpreter. When it is typed python in the shell or
command prompt, the python interpreter becomes active with a >>> prompt and waits for the
user commands.

Now , user can type any valid python expression at the prompt. Python reads the
typed expression, evaluates it and prints the result.

b. Running Python Scripts inIDLE:


 Goto File menu click on New File (CTRL+N) and write the code and save add.py
a=input("Enter a value")
b=input("Enter b value ")
c=a+b
print "The sum is",c
 And run the program bypressingF5 or Run→RunModule.

Page 12
PYTHON PROGRAMMING KG College of Arts and Science

c. Running python scripts in CommandPrompt:


 Before going to run, have to check the PATH in environmentvariables.
 Open the text editor, type the following text and save it ashello.py.
print "hello"
 And run this program by calling python hello.py. Make sure, the change to the
directory where the file is saved before doing it.

1.6 VARIABLES:

Python variables: variables are just names.Variables are nothing but reserved memory
locations to store values. This means that when a variables are creates, it reserve some space in
memory. Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to variables,
user can store integers, decimals or characters in these variables. In Python, everything—
booleans, integers, floats, strings, even large data structures, functions, and programs—is
implemented as an object. An object is like a clear plastic box that contains a piece of data. The
object has a type, such as boolean or integer, that determines what can be done with the data.
Python is strongly typed, which means that the type of an object does not change, even if its
value is mutable. Assignment does not copy a value; it just attaches a name to the object that
contains the data. The type also determines if the data value contained by the box can be
changed (mutable) or is constant (immutable).

Assigning Values to Variables :


Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when a value to a variable is assigned. The equal sign (=)
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 value stored in the variable. For example –

Page 13
PYTHON PROGRAMMING KG College of Arts and Science

Another Example:
In Python, use = to assign a value to a variable.
>>> a = 7
>>> print(a) 7
Multiple Assignments to variables:
Python allows you to assign a single value to several variables simultaneously.
For example –
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.
For example –
a, b, c = 1, 2.5, ”mothi”
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.

The name is a reference to a thing rather than the thing itself.In Python, to know the type of
anything (a variable or a literal value), use type( thing ). Example with different literal values
(58, 99.9, abc) and different variables (a, b):
>>> type(a)
<class ‗int‘>
>>> type(b)
<class ‗int‘>
>>> type(58)
<class ‗int‘>
>>> type(99.9)
<class ‗float‘>
>>> type('abc')
<class ‗str‘>

Rules for defining a Variables in Python :


 Variable names can only contain these characters:
 Lowercase letters (a through z) ,
 Uppercase letters (A through Z),
 Digits (0 through 9),
 Digits (0 through 9),

Page 14
PYTHON PROGRAMMING KG College of Arts and Science

 Underscore (_)
 Names cannot begin with a digit.
 Also, Python treats names that begin with an underscore in special ways
 These are valid names:
 a , a1,a_b_c___95,_abc,_1a
 These names, however, are not valid: 1,1a,1_

1.7 KEYWORDS / RESERVED WORDS :


The following list shows the Python keywords. These are reserved words and cannot be used
as constant or variable or any other identifier names.Reserved words (also called keywords) are
defined with predefined meaning and syntax in the language.Reserved words can‘t be used as
identifiers for other programming elements like name of variable, function etc.
Python 3 has 33 keywords while Python 2 has 30. The print has been removed from
Python 2 as keyword and included as built-in function. All the Python keywords contain
lowercase letters only.

1.8 COMMENTS:

 Comments are the way to improve the readability of a code,


 A comment is text that doesn‘t affect the outcome of a code,
 it is just a piece of text to let someone know what you have done in a program or what is
being done in a block of code.
 This is especially helpful when someone else has written a code and are analysing it for
bug fixing or making a change in logic,
 Reading a comment can understand the purpose of code much faster then by just going
through the actual code.
 # This is just a text, it won't be executed.
 print("Python comment example")
 Output: Python comment example

Process finished with exit code

TYPES OF COMMENTS IN PYTHON :


 There are two types of comments in Python.
1. Single line comment 2.Multiple line comment
1.Single line comment :
 In python use # special character to start the comment.
 Few examples to understand the usage.

Page 15
PYTHON PROGRAMMING KG College of Arts and Science

# This is just a comment.

Anything written here is ignored by Python

2.Multi-line comment:

To have a multi-line comment in Python, use triple single quotes at the beginning and at the end
of the comment, as shown below.

''' This is a

multi-line

comment '''

1.8 DATA TYPES


Data types are the classification or categorization of data items. Types of Data Types
are Scalar Types,Sequence Types, Mapping Types and Set Types . Python supports the
following built-in data types.
1.8.1 SCALAR TYPES :
int :
Positive or negative whole numbers (without a fractional part) e.g. -10, 10, 456, 4654654.
Example:

>>> print(24656354687654+2) 24656354687656


>>> print(20) 20
>>> print(0b10) 2
>>> print(0B10) 2
>>> print(0X20) 32
>>> 20
20
>>>0b10 2
>>> a=10
>>> print(a) 10

# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>

Page 16
PYTHON PROGRAMMING KG College of Arts and Science

Float:
Any real number with a floating-point representation in which a fractional component is
denoted by a decimal symbol or scientific notation e.g. 1.23, 3.4556789e2.
Example:

>>> y=2.8 Example:


>>> y 2.8
>>> y=2.8
>>> print(type(y)) x = 35e3 y = 12E4
<class 'float'> z = -87.7e100
>>> type(.4) print(type(x)) print(type(y)) print(type(z))
<class 'float'> Output:
>>> 2. <class 'float'>
<class 'float'>
2.0
<class 'float'>
Complex:
A number with a real and imaginary component represented as x + 2y.
Bool:
Data with one of two built-in values True or False. Notice that 'T' and 'F' are
capital. true and false are not valid booleans and Python will throw an error for them.
Example:

>>> type(True) None:


<class 'bool'>
>>> type(False) The None
<class 'bool'> represent
s the null
object in Python. A None is returned by functions that don't explicitly return a value.
Strings :
 Strings are a sequence of characters.
 strings in Python are immutable.
 can‘t change a string in-place,
but can copy parts of strings to another string to get the same effect
 Python string by enclosing characters in either single quotes or double quotes, as
demonstrated in the following:
>>> 'Snap'
 'Snap'

>>> "Crackle"
 'Crackle'
 Triple quotes aren‘t very useful for short strings like these.
 Their most common use is to create multiline strings
>>> poem = '''There was a Young Lady of Norway,
 ... Who casually sat in a doorway;
 ... When the door squeezed her flat,
 ... She exclaimed, "What of that?"
 ... This courageous Young Lady of Norway.'''

 >>> print(poem)
 >>> poem
Page 17
PYTHON PROGRAMMING KG College of Arts and Science

Convert Data Types by Using str()


 can convert other Python data types to strings by using the str() function:
>>> str(98.6)
 '98.6'
>>> str(1.0e4)
 '10000.0'
>>> str(True)
 'True'

Python uses the str() function internally when print() is called with objects that are not strings
and when doing string interpolation. To get a single character from a string, specify its offset
inside square brackets after the string‘s name.
 The first (leftmost) offset is 0, the next is 1, and so on.
 The last (rightmost) offset can be specified with –1 so you don‘t have to count; going to
the left are –2, –3, and so on.
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[0] 'a'
>>> letters[1] 'b'
>>> letters[-1] 'z'
>>> letters[-2] 'y'

1.8.2 SEQUENCE TYPE


A sequence is an ordered collection of similar or different data types. Python has the
following built-in sequence data types:
 String: A string value is a collection of one or more characters put in single, double or
triple quotes.
 List: A list object is an ordered collection of one or more data items, not necessarily of
the same type, put in square brackets.
 Tuple: A Tuple object is an ordered collection of one or more data items, not necessarily
of the same type, put in parentheses.

1.8.3 MAPPING TYPE

Dictionary: A dictionary Dict() object is an unordered collection of data in


akey:value pair form. A collection of such pairs is enclosed in curly brackets. For
example: {1:"Steve", 2:"Bill", 3:"Ram", 4: "Farha"}

1.8.4 SET TYPES

 Set:Set is mutable, unordered collection of distinct hashable objects. The set is a Python
implementation of the set in Mathematics. A set object has suitable methods to perform
mathematical set operations like union, intersection, difference, etc.
 Frozenset: Frozenset is immutable version of set whose elements are added from other
iterates.

Mutable and Immutable Types


Data objects of the above types are stored in a computer's memory for processing.
Some of these values can be modified during processing, but contents of others can't be
altered once they are created in the memory. Numbers, strings, and Tuples are immutable,
which means their contents can't be altered after creation

Page 18
PYTHON PROGRAMMING KG College of Arts and Science

1.9 OPERATORS:

Operators are special symbols that perform some operation on operands and returns
the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic
add operation on numeric left operand 5 and the right side operand 6 and returns a sum of two
operands as a result.
Python includes the operator module that includes underlying methods for each
operator. For example, the + operator calls the operator.add(a,b) method.

Example: Operator Methods

>>> 5 + 6 11
>>> import operator
>>> operator.add(5, 6) 11
>>> operator.__add__(5, 6) 11

Above, expression 5 + 6 is equivalent to the expression operator.add(5,


6) and operator.__add__(5, 6). Many function names are those used for special methods,
without the double underscores (dunder methods). For backward compatibility, many of these
have functions with the double underscores kept.

Python includes the following categories of operators:

 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Identity Operators
 Membership Test Operators
 Bitwise Operators

Page 19
PYTHON PROGRAMMING KG College of Arts and Science

 ARITHMETIC OPERATORS

Arithmetic operators perform the common mathematical operation on the numeric


operands. The arithmetic operators return the type of result depends on the type of operands,
as below.

 If either operand is a complex number, the result is converted to complex;


 If either operand is a floating point number, the result is converted to floating
point;
 If both operands are integers, then the result is an integer and no conversion is
needed.

The following table lists all the arithmetic operators in Python:

Operation Operator Function Example


Addition: Sum of two + operator.add(a,b) >>> x = 5; y = 6
operands >>> x + y11
>>>import operator
>>> operator.add(5,6)11
Subtraction: Left - operator.sub(a,b) >>> x = 10; y = 5
operand minus right >>> x – y 5
operand >>>import operator
>>> operator.sub(10, 5) 5
Multiplication * operator.mul(a,b) >>> x = 5; y = 6
>>> x * y30
>>>import operator
>>> operator.mul(5,6) 30
Exponentiation: Left ** operator.pow(a,b) >>> x = 2; y = 3
operand raised to the >>> x ** y8
power of right >>>import operator
>>> operator.pow(2, 3) 8
Division / operator.truediv(a,b) >>> x = 6; y = 3
>>> x / y2
>>> import operator
>>> operator.truediv(6,
3)2
Floordivision: equivilant // operator.floordiv(a,b) >>> x = 6; y = 5
to math.floor(a/b) >>> x // y1
>>> import operator>>>
operator.floordiv(6,5)1
Modulus: Reminder % operator.mod(a, b) >>> x = 11; y = 3
of a/b >>> x % y 12
>>> import operator
>>> operator.mod(11, 3)2

Page 20
PYTHON PROGRAMMING KG College of Arts and Science

ASSIGNMENT OPERATORS:
The assignment operators are used to assign values to variables. The following

Operator Function Example


= >>> x = 5;>>> x 5
+= operator.iadd(a,b) >>> x = 5>>> x += 510>>> import operator
>>> x = operator.iadd(5, 5)10
-= operator.isub(a,b) >>> x = 5>>> x -= 23>>> import operator
>>> x = operator.isub(5,2)
*= operator.imul(a,b) >>> x = 2>>> x *= 36>>> import operator
>>> x = operator.imul(2, 3)
/= operator.itruediv(a,b) >>> x =6>>> x /= 32>>> import operator
>>> x = operator.itruediv(6, 3)
//= operator.ifloordiv(a,b) >>> x = 6>>> x //= 51>>> import operator
>>> operator.ifloordiv(6,5)
%= operator.imod(a, b) >>> x = 11>>> x %= 32>>> import operator
>>> operator.imod(11, 3)2
&= operator.iand(a, b) >>> x = 11>>> x &= 31>>> import operator
>>> operator.iand(11, 3)1
|= operator.ior(a, b) >>> x = 3>>> x |= 47>>> import operator
>>> operator.mod(3, 4)7
^= operator.ixor(a, b) >>> x = 5>>> x ^= 27>>> import operator
>>> operator.ixor(5, 2)7
>>= operator.irshift(a, b) >>> x = 5>>> x >>= 21>>> import operator
>>> operator.irshift(5, 2)1
<<= operator.ilshift(a, b) >>> x = 5>>> x <<= 220>>> import operator
>>> operator.ilshift(5, 2)20

Page 21
PYTHON PROGRAMMING KG College of Arts and Science

COMPARISON OPERATORS :
The comparison operators compare two operands and return a boolean either True or
False. The following table lists comparison operators in Python.
Operator Function Description Example in Python Shell
> operator.gt(a,b) True if the left operand >>> x = 5; y = 6
is higher than the right >>> x > y False
one >>>import operator
>>> operator.gt(5,6)False
< operator.lt(a,b) True if the left operand >>> x = 5; y = 6
is lower than right one >>> x < yTrue
>>> import operator
>>>operator.add(5,6)True
== operator.eq(a,b) True if the operands >>> x = 5; y = 6
are equal >>> x == yFalse
>>> import operator
>>> operator.eq(5,6)False
!= operator.ne(a,b) True if the operands >>> x = 5; y = 6
are not equal >>>x != y True
>>> import operator
>>> operator.ne(5,6) True
>= operator.ge(a,b) True if the left operand >>> x = 5; y = 6
is higher than or equal >>> x >= yFalse
to the right one >>> import operator
>>> operator.ge(5,6) False
<= operator.le(a,b) True if the left operand >>> x = 5; y = 6
is lower than or equal >>> x <= yTrue
to the right one >>> import operator
>>> operator.le(5,6)True

LOGICAL OPERATORS
The logical operators are used to combine two boolean expressions. The logical
operations are generally applicable to all objects, and support truth tests, identity tests, and
boolean operations.
Operator Description Example
and True if both are true >>> x = 5; y = 6>>> x > 1 and y
<10True
or True if at least one is true >>> x = 5; y = 6>>> x > 6 or y
<10True
not Returns True if an >>> x = 5>>> not x > 1 False
expression evalutes to false and
vice-versa

Page 22
PYTHON PROGRAMMING KG College of Arts and Science

IDENTITY OPERATORS
The identity operators check whether the two objects have the same id value e.i. both
the objects point to the same memory location.
Operator Function Description Example in Python
Shell
is operator.is_(a,b) True if both are true >>> x = 5; y = 6>>> x
is y False>>> import
operator>>>operator.is
_(x,y)False
is not operator.is_not(a,b) True if at least one is >>> x = 5; y = 6>>> x
true is not yTrue>>> import
operator>>>
operator.is_not(x,
y)True

MEMBERSHIP TEST OPERATORS


The membership test operators in and not in test whether the sequence has a given
item or not. For the string and bytes types, x in y is True if and only if x is a substring of y.
Operator Function Description Example in Python Shell
in operator.contains(a,b) Returns True >>> nums = [1,2,3,4,5]
if the >>> 1 in nums True>>> 10 in
sequence nums False>>> 'str' in
contains the 'string'True>>> import
specified item operator>>>
else returns operator.contains(nums,
False. 2)True
not in Notoperator.contains(a,b) Returns True >>> nums = [1,2,3,4,5]>>> 1
if the not in nums False>>> 10 not
sequence does in nums True>>> 'str' not in
not contains 'string'False>>> import
the specified operator>>> not
item, else operator.contains(nums,
returns False. 2)False

Page 23
PYTHON PROGRAMMING KG College of Arts and Science

BITWISE OPERATORS

Operator Function Description Example in Python Shell

& operator.and_(a Sets each bit to 1 if >>> x=5; y=10>>> z=x &
,b) both bits are 1. y >>> z0>>> import
operator>>> operator.and_(x,
y)0
| operator.or_(a, Sets each bit to 1 if >>> x=5; y=10>>> z=x |
b) one of two bits is 1. y >>> z15>>> import
operator>>> operator.or_(x,
y)15
^ operator.xor(a, Sets each bit to 1 if >>> x=5; y=10>>> z=x ^
b) only one of two bits is y >>> z15>>> import
1. operator>>> operator.xor(x,
y)15
~ operator.invert( Inverts all the bits. >>> x=5>>> ~x-6>>> import
a) operator>>>
operator.invert(x)-6
<< operator.lshift( Shift left by pushing >>> x=5>>> x<<220>>>
a,b) zeros in from the right import operator>>>
and let the leftmost operator.lshift(x,2)20
bits fall off.
>> operator.rshift( Shift right by pushing >>> x=5>>> x>>21>>>
a,b) copies of the leftmost import operator>>>
bit in from the left, operator.rshift(x,2)1
and let the rightmost
bits fall off.
Bitwise operators perform operations on binary operands.

1.10 INPUT STATEMENTS:

To get input from the user , use the input function. When the input function is called the
program stops running the program, prompts the user to enter something at the keyboard by
printing a string called the prompt to the screen, and then waits for the user to press the Enter
key. The user types a string of characters and presses enter. Then the input function returns
that string and Python continues running the program by executing the next statement after the
input statement.
Python provides the function input(). input has an optional parameter, which is the
prompt string.To get input from the user, should use input function.
 Syntax
 variable = input('Prompt message')
 where,
 variable - where user want to store the input
 input() - Used to read the user input
 Prompt message - will be printed on the screen while getting the input

Page 24
PYTHON PROGRAMMING KG College of Arts and Science

For example,

 The input function reads the input and always converts it into a string. So, need to
typecast the input based on the need of the user. Using int() function, converts the string
input to integer.
 The below program will get two numbers from the user and print their sum.
 #Below inputs are explicitly converted into integer
 #using int() function
 a = int(input('Enter first number'))
 b = int(input('Enter second number'))
 ans = a + b
 print(ans)

#Example 2
 #Ask for the user's name and print it:
 print('Enter your name:')
 x = input()
 print('Hello, ' + x)
# Example 3
 # Taking input from the user as float
 num =float(input("Enter number "))
 add = num + 1
 # output
 print(add)
#Example 4
 # Taking input from the user as list
 li =list(input("Enter number "))
 # output
 print(li)
 # Taking input from the user as tuple
 num =tuple(input("Enter number "))
 # output
 print(num)

#Example 5
# This program adds two numbers provided by the user
# Store input numbers
 num1 = input('Enter first number: ')
 num2 = input('Enter second number: ')
 # Add two numbers

Page 25
PYTHON PROGRAMMING KG College of Arts and Science

 sum = float(num1) + float(num2)


 # Display the sum
 print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

MULTIPLE INPUT STATEMENT IN PYTHON :


Python program showing how to multiple input using #split (ie) taking two inputs at a time
 #multiple inputs in Python using input
 x, y = int(input("Enter First Name: ")), int(input("Enter Last Name: ") )
 print("First Number is: ", x)
 print("Second Number is: ", y)
 print("Sum of numbers ", x+y)
# Alternative statements in Python
print('The sum is %.1f' %(float(input('Enter first number: '))+float(input('Enter second number:
'))))

#Another Example
# Python program showing how to multiple input using #split (ie) taking two inputs at a time

 x, y = input("Enter a two value: ").split()


 print("Number of boys: ", x)
 print("Number of girls: ", y)
 print()
 # taking three inputs at a time
 x, y, z = input("Enter a three value: ").split(‗,‘)
 print("Total number of students: ", x)
 print("Number of boys is : ", y)
 print("Number of girls is : ", z)
 print()

1.11 OUTPUT STATEMENT:


Use the print() function or print keyword to output data to the standard output device
(screen). This function prints the object/string written in function.
The actual syntax of the print() function is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Here, objects is the value(s) to be printed.
The sep separator is used between the values. It defaults into a space character. After
all values are printed, end is printed. It defaults into a new line ( \n ).
 Python provides the print() function to display output to the console.
Syntax: print(value(s), sep= ‗ ‗, end = ‗\n‘, file=file, flush=flush)
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed

Page 26
PYTHON PROGRAMMING KG College of Arts and Science

sep=‘separator‘ : (Optional) Specify how to separate the objects, if there is more than
one.Default :‘ ‗
end=‘end‘: (Optional) Specify what to print at the end.Default : ‗\n‘
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Returns: It returns output to the screen.

O/P - end = ―‖ statement


 The end keyword is used to specify the content that is to be printed at the end of the
execution of the print() function.
 By default, it is set to ―\n‖, which leads to the change of line after the execution of print()
statement.

#Example:

# This line will automatically add a new line before the # next print statement

print ("Welcome to KGCAS ")

# This print() function ends with "**" as set in the end argument.

print ("Python is an interpreted language ", end= "**")

O/P separator
 The print() function can accept any number of positional arguments. These arguments
can be separated from each other using a ―,‖ separator.

Page 27
PYTHON PROGRAMMING KG College of Arts and Science

 These are primarily used for formatting multiple statements in a single print() function.

#Example:
b = "Python for"
print("KGCAS ", b , "CT")
#examples
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
O/P
1234
1*2*3*4
1#2#3#4&

1.11.1 Output - Print - File Argument


Contrary to popular belief, the print() function doesn‘t convert the messages into text on the
screen. These are done by lower-level layers of code, that can read data(message) in bytes.The
print() function is an interface over these layers, that delegates the actual printing to a stream or
file-like object. By default, the print() function is bound to sys.stdout through the file argument.

 import io
 # declare a dummy file
 dummy_file = io.StringIO()
 # add message to the dummy file
 print('Hello CT students!!', file=dummy_file)
 # get the value from dummy file
 dummy_file.getvalue()
 OUTPUT
'Hello CT Students!!\n'
 f1 = open('python.txt', 'w')
 print('Welcome to Python Programming', file = f1)
 f1.close()
 OUTPUT
 #DISPLAYED IN python.txt file

1.11.2 OUTPUT FORMATTING


 To format the output to make it look attractive. This can be done by using the str.format()
method. This method is visible to any string object.

>>> x = 5; y = 10

>>> print('The value of x is {} and y is {}'.format(x,y))

 The value of x is 5 and y is 10


 Here, the curly braces {} are used as placeholders.

User can specify the order in which they are printed by using numbers (tuple index).
 # Declaring a variable - Another example
 name = "Students"

Page 28
PYTHON PROGRAMMING KG College of Arts and Science

 # Output
 print(f'Hello {name}! How are you?')
 #Another example
 print('I love my {0} and {1}'.format('mom','dad'))
 print('I love my {1} and {0}'.format('mom','dad'))

 use ‗%‘ operator. % values are replaced with zero or more value of elements.
 # Taking input from the user
 >>>num = int(input("Enter a value: "))
 >>>add = num + 5
 # Output
 print("The sum is %d" %add)
 #Another example
 >>> x = 12.3456789
 >>> print('The value of x is %3.2f' %x)
 The value of x is 12.35
 >>> print('The value of x is %3.4f' %x)
 The value of x is 12.3457

Indentation
Code blocks are identified by indentation rather than using symbols like curly braces.
Without extra symbols, programs are easier to read. Also, indentation clearly identifies which
block of code a statement belongs to. Of course, code blocks can consist of single statements,
too. When one is new to Python, indentation may come as a surprise. Humans generally
prefer to avoid change, so perhaps after many years of coding with brace delimitation, the
first impression of using pure indentation may not be completely positive. However, recall
that two of Python's features are that it is simplistic in nature and easy toread.

Python does not support braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation. All the continuous
lines indented with same number of spaces would form a block. Python strictly follow
indentation rules to indicate the blocks.

Page 29
PYTHON PROGRAMMING KG College of Arts and Science

END OF UNIT – I

UNIT II
Page 30
PYTHON PROGRAMMING KG College of Arts and Science
CONTROL STATEMENTS: Control Flow and Syntax – Indenting – if Statement – statements
and expressions- string operations- Boolean Expressions –while Loop – break and continue – for
Loop. LISTS: List-list slices – list methods – list loop – mutability – aliasing – cloning lists –
list parameters. TUPLES: Tuple assignment, tuple as return value –Sets – Dictionaries

2. CONTROL STATEMENTS:
Conditional Statements are features of a programming language, which perform different
computations or actions depending on whether the given condition evaluates to true or false.
Conditional statements in python are of 3 types

i) if statement
ii)if else statement
iii)if elif statement
iv)Nested if else

i) if Statement:
if Statement is used to run a statement conditionally i.e. if given condition is true then
only the statement given in if block will be executed.

Example:
if (percentage > 33):
Syntax: print (―Pass‖)
if <condition>:
<if statement block >
Explanation :
In the above code if value of percentage is above 33 then
only the message ―Pass‖ will be printed.
Flow Chart

ii)if else Statement:

Page 31
PYTHON PROGRAMMING KG College of Arts and Science
Statement In the case of if else statement If given condition is true then the statement
given in if block will be executed otherwise(else) the statements written in else block will be
executed

Syntax: Example:
<if statement block > if (percentage > 33):
else: print (―Pass‖)
<else statement block> else:
print(―Fail‖)

Explanation :
In the above code if value of percentage is above 33 then only the message ―Pass‖ will be
printed otherwise it will print ―Fail‖

iii)if….elif Statement:
if elif is used for execution OF STATEMENTS based on several alternatives. Here we
use one or more elif (short form of else if) clauses. Python evaluates each condition in turn and
executes the statements corresponding to the first if that is true. If none of the expressions are
true, and an else clause will be executed.

if <condition>: if (percentage >90):


<statement(s)> print(―Outstanding‖)
elif <condition>: elif (percentage >80):
<statement(s)> print (―Excellent‖)
. elif (percentage >70):
Explanation : print (―VeryGood‖)
.
In the above code elif (percentage >60):
else: print (―Good‖)
<statement(s)> elif (percentage >33):
print (―Pass‖)
else :
print(―Fail‖)
if value of percentage is above 90 then it will print ―Outstanding‖
if value of percentage is above 80 then it will print ―Excellent‖
Page 32
PYTHON PROGRAMMING KG College of Arts and Science
if value of percentage is above 70 then it will print ―Very Good‖
if value of percentage is above 60 then it will print ―Good‖
if value of percentage is above 80 then it will print ―Pass‖
if no condition is true then it will print ―Fail‖
In above code only 1 condition can be true at a time if no condition is true then else statement
will be executed.

iv)Nested if else Statement:


A nested if is an if statement that is the target of another if statement. Nested if statement
means an if statement within another if statement.

Syntax: Example:
if (<condition1>): if color =‖red‖:
statement(s) if item=‖fruit‖:
if (<condition2>): print(― It is an Apple‖)
statement(s) else :
else print(―It may be Tomato or Rose‖)
else: else:
if (<condition3>): if color=‖Yellow‖:
statement(s) print(―It is a Banana‖)
else else
Statement(s) print(―It may be corn or Marigold ‖)

String:
Strings in Python are identified as a contiguous set of characters represented in
thequotation marks. Python allows for either pairs of single or double quotes.
 'hello' is the same as "hello".
Strings can be output to screen using the print function.
For example: print("hello").

>>> print("KGCAS college") KGCAS


college
>>> type("KGCAS college")
<class 'str'>
>>> print('KGCAS college') KGCAS college
>>> " "
''

To include either type of quote character within the string, the simplest way is to delimit the
string with the other type. If a string is to contain a single quote, delimit it with double quotes
and vice versa:
>>>print("KGCAS is an affiliated (') college")
KGCAS is an affiliated (') college
>>> print('KGCAS is an affiliated (") college')
KGCAS is an affiliated (") college

Suppressing Special Character:


Specifying a backslash (\) in front of the quote character in a string ―escapes‖ it and
causes Python to suppress its usual special meaning. It is then interpreted simply as a literal
Page 33
PYTHON PROGRAMMING KG College of Arts and Science
single quote character.
Example:
>>> print("Hai (\')Hello ") Hai (') Hello
>>> print('Hai (\") Hello') Hai (") Hello
The following is a table of escape sequences which cause Python to suppress the usual
special interpretation of a character in a string:
Example:
>>> print('a\....b')
a.b
>>> print('a\ b\c')
abc
>>> print('a \n b') ab
>>> print("KGCAS \n college")
KGCAS
college
Escape Usual Interpretation of
Sequence Character(s) After Backslash ―Escaped‖ Interpretation

\' Terminates string with single quote opening Literal single quote (') character
delimiter
\" Terminates string with double quote opening Literal double quote (")
delimiter character
\newline Terminates input line Newline is ignored
\\ Introduces escape sequence Literal backslash (\) character
In Python (and almost all other common computer languages), a tab
character can be specified by the escape sequence \t:
Example:
>>> print('a \n b') ab
>>> print("KGCAS \n college")
KGCAS
college
>>> print("a\tb")
a b

Boolean Expression:
A boolean expression is an expression that is either true or false. The following examples
use the operator ==, which compares two operands and produces True if they are equal and False
otherwise:

Page 34
PYTHON PROGRAMMING KG College of Arts and Science
Example :

>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the type bool; they are not strings:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>

Iteration:

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


as long as the condition is true. Repeated execution of a set of statements with the help of loops
is called iteration.
Loops statements are used when we need to run same code again and again, each time with a
different value.

2.2 LOOP STATEMENTS:

In Python Iteration (Loops) statements are of three types:


1. while Loop
2. for Loop
3. Nested For Loops

While loop:

Loops are either infinite or conditional. Python while loop keeps reiterating a
block of code defined inside it until the desired condition is met.
The while loop contains a boolean expression and the code inside the loop is
repeatedly executed as long as the boolean expression is true.
The statements that are executed inside while can be a single line of code or a
block of multiple statements.
Example
Syntax: i=1
while(expression): while i<=6:
Statement(s) print("KGCAS college") i=i+1

Flowchart:

Page 35
PYTHON PROGRAMMING KG College of Arts and Science

i=1
while i<=3: print("KGCAS",end=" ") j=1
while j<=1:
print("CSE DEPT",end="") j=j+1
i=i+1 print()
Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/wh2.py KGCAS
KGCAS CSE DEPT KGCAS

for loop:
Python for loop is used for repeated execution of a group of statements for the desired
number of times. It iterates over the items of lists, tuples, strings, the dictionaries and other
iterable objects

Syntax: for var in sequence:statement(s) A sequence of values assigned to var in each


iteration Holds the value of item
in sequence in each iteration

#Sample Program:
numbers = [1, 2, 4, 6, 11, 20] seq=0
for val in numbers: seq=val*val print(seq)

Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/fr.py 1
4
16
36
121
400

Page 36
PYTHON PROGRAMMING KG College of Arts and Science
Flowchart:

Iterating over a list:


#list of items
list = ['K','G','C','A','S']
i=1

#Iterating over the list for item in list:


print ('college ',i,' is ',item) i = i+1

Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/lis.py
college 1 is K
college 2 is G
college 3 is C
college 4 is A
college 5 is S

Iterating over a Tuple:


tuple = (2,3,5,7)
print ('These are the first four prime numbers ')
#Iterating over the tuple
for a in tuple:
print (a)

Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/fr3.py These are the first
four prime numbers
2
3
Page 37
PYTHON PROGRAMMING KG College of Arts and Science
5
7

Iterating over a dictionary:


#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}

#Iterating over the dictionary to print keys print ('Keys are:')

for keys in college:


print (keys)

#Iterating over the dictionary to print values print ('Values are:')


for blocks in college.values():
print(blocks)

Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/dic.py Keys are:
ces it ece
Values are:
block1 block2 block3

Nested For loop:


When one Loop defined within another Loop is called Nested Loops.
Syntax:
for val in sequence:
for val in sequence:

statements statements

# Example 1 of Nested For Loops (Pattern Programs)


for i in range(1,6): for j in range(0,i):
print(i, end=" ")
print('')
Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/nesforr.py 1
22
333
4444
55555

# Example 2 of Nested For Loops (Pattern Programs)


for i in range(1,6):
for j in range(5,i-1,-1):
print(i, end=" ")
print('')
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/nesforr.py
Output:
11111
2222
Page 38
PYTHON PROGRAMMING KG College of Arts and Science
333
44

Break:
The break statement terminates the loop containing it and control of the program flows
to the statement immediately after the body of the loop. If break statement is inside a nested
loop (loop inside another loop), break will terminate the innermost loop.

Flowchart:

The following shows the working of break statement in for and while loop:
for var in sequence:
# code inside for loop If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop

while test expression


# code inside while loop If condition:
break (if break condition satisfies it jumps to outside loop) # code inside while loop
# code outside while loop

Example:
for val in "KGCAS COLLEGE":
if val == " ":
break
print(val)
print("The end")

Output:

Page 39
PYTHON PROGRAMMING KG College of Arts and Science
KGCAS
The end

# Program to display all the elements before number 88


for num in [11, 9, 88, 10, 90, 3, 19]:
print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop") break

Output:
11
9
88
The number 88 is found

Terminating the loop


for letter in "Python":
# First Example
if letter == "h":
break
print("Current Letter :", letter )

Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/br.py =
Current Letter : P
Current Letter : y
Current Letter : t

Continue:
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.

Flowchart:

The following shows the working of break statement in for and while loop:

for var in sequence:


# code inside for loop If condition:
continue (if break condition satisfies it jumps to outside loop)
Page 40
PYTHON PROGRAMMING KG College of Arts and Science
# code inside for loop
# code outside for loop

while test expression


# code inside while loop If condition:
continue(if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop

Example:
# Program to show the use of continue statement inside loops
for val in "string":
if val == "i": continue
print(val) print("The end") Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/cont.py
s
t
r
n
g
The end

# program to display only odd numbers for num in [20, 11, 9, 66, 4, 89, 44]:

# Skipping the iteration when number is even


if num%2 == 0:
continue
# This statement will be skipped for all even numbers
print(num)

Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/cont2.py 11
9
89

for letter in "Python":


# First Example
if letter == "h":
continue
print("Current Letter :", letter) Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/con1.py
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n

2.3 LISTS, TUPLES, DICTIONARIES


Lists:
List operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple
Page 41
PYTHON PROGRAMMING KG College of Arts and Science
comprehension; Dictionaries: operations and methods, comprehension;
•It is a general purpose most widely used in data structures
•List is a collection which is ordered and changeable and allows duplicate members. (Grow and
shrink as needed, sequence type, sortable).
•To use a list, you must declare it first. Do this using square brackets and separate values with
commas.
•We can construct / create list in many ways.
EXAMPLE:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
>>> x=list()
>>> x []
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
2.3.1 LIST OPERATIONS:
These operations include indexing, slicing , adding ,multiplying, and checking for membership
Basic List Operations:
Lists respond to the + and * operators much like strings; they mean concatenation and repetition
here to, except that the result is a new list, not a string.

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership


for x in [1, 2, 3]: print x, 123 Iteration

2.3.1.1 Indexing, Slicing, and Matrixes


Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
Assuming following input −
L = ['KGCAS', 'college', 'KGCAS!']
Python Expression Results Description

L[2] MRCET Offsets start at zero

Page 42
PYTHON PROGRAMMING KG College of Arts and Science
L[-2] college Negative: count from the right

L[1:] ['college', 'MRCET!'] Slicing fetches sections

2.3.2 List slices:


>>> list1=range(1,6)
>>> list1 range(1, 6)
>>> print(list1) range(1, 6)
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1] [1]
>>> list1[2:5] [3, 4, 5]
>>> list1[:6] [1, 2, 3, 4, 5, 6]
>>> list1[1:2:4] [2]
>>> list1[1:8:2] [2, 4, 6, 8]
2.3.3 List methods:
The list data type has some more methods. Here are all of the methods of list objects:
i)del()
ii)append()
iii)extend()
iv)insert()
v)pop()
vi)remove()
vii)reverse()
viii)sort()
ix)min
x)max
xi)multiply
xii)copy
xiii)concatenate

i)delete:
Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x [5, 8, 6]

Page 43
PYTHON PROGRAMMING KG College of Arts and Science
>>> del(x)
>>> x # complete list gets deleted
ii)append:
Append an item to a list
>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
[1, 5, 8, 4, 10]
iii)extend:
Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
iv)insert:
To add an item at the specified index, use the insert () method:
>>> x=[1,2,4,6,7]
>>> x.insert(2,10)
#insert(index no, item to be inserted)
>>> x
[1, 2, 10, 4, 6, 7]
>>> x.insert(4,['a',11])
>>> x
[1, 2, 10, 4, ['a', 11], 6, 7]
v)pop:
The pop() method removes the specified index, (or the last item if index is not specified)
or simply pops the last item of list and returns the item.
>>> x=[1, 2, 10, 4, 6, 7]
>>> x.pop() 7
>>> x
[1, 2, 10, 4, 6]
>>> x=[1, 2, 10, 4, 6]
>>> x.pop(2) 10
>>> x
[1, 2, 4, 6]
vi)remove:
Page 44
PYTHON PROGRAMMING KG College of Arts and Science
The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
[1, 2, 10, 4, 6]
>>> x.remove(4)
>>> x
[1, 2, 10, 6]
vii)reverse:
Reverse the order of a given list.
>>> x=[1,2,3,4,5,6,7]
>>> x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]
viii)sort:
Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]
>>> x.sort()
>>> x
[1, 2, 3, 4, 5, 6, 7]
>>> x=[10,1,5,3,8,7]
>>> x.sort()
>>> x
[1, 3, 5, 7, 8, 10]

ix)max()
 used to compute the maximum of the values passed in its argument and
 lexicographically largest value if strings are passed as arguments.
 Syntax :
 max(a,b,c,..,key,default)
 Parameters : a,b,c,.. : similar type of data.
 key : key function where the iterables are passed and comparison is performed
 default : default value is passed if the given iterable is empty
 Return Value : Returns the maximum of all the arguments.
 Exceptions : Returns TypeError when conflicting types are compared.
#Example
 max()
 # printing the maximum of 4,12,43.3,19,100
 print("Maximum of 4,12,43.3,19 and 100 is : ",end="")
 print (max( 4,12,43.3,19,100 ) )
# TYPE ERROR-EXAMPLES
Page 45
PYTHON PROGRAMMING KG College of Arts and Science
#code to demonstrate the Exception of min() and max()
# printing the minimum of 4,12,43.3,19, "GeeksforGeeks"
# Throws Exception
print("Minimum of 4,12,43.3,19 and Python is : ",end="")
print (min( 4,12,43.3,19,"Python" ) )
x)min()
 used to compute the minimum of the values passed in its argument and lexicographically
smallest value if strings are passed as arguments. The min() function returns the smallest
item in an iterable. It can also be used to find the smallest item between two or more
parameters.
 Syntax : min(a,b,c,.., key,default)
 Parameters : a,b,c,.. : similar type of data.
 key : key function where the iterables are passed and comparison is performed
 default : default value is passed if the given iterable is empty
 Return Value : Returns the minimum of all the arguments.
 Exceptions : Returns TypeError when conflicting types are compared.
#Example
numbers = [9, 34, 11, -4, 27]
# find the smallest number
min_number = min(numbers)
print(min_number)
# Output: -4
xi)multiply
 Python also allows multiplying the list n times. The resultant list is the original list iterate
n times.
 #example
 m=[1,2,'Python']
 print(m*2)
 #output
 [1, 2, 'Python', 1, 2, 'Python']

xii) concatenate()
 Concatenate operation is used to merge two lists and return a single list.
 The + sign is used to perform the concatenation.
 Note that the individual lists are not modified, and a new combined list is returned.
 myList=[1, 2, 'Welcome ']
 yourList = [4, 5, 'Python', 'is fun!']
 print(myList+yourList)

xiii)copy()
 copy() method returns a copy of the specified list.
 Syntax: list.copy()

 Copy the fruits list:
 fruits = ['apple', 'banana', 'cherry', 'orange']
 x = fruits.copy()

2.3.4 LIST LOOP:


Page 46
PYTHON PROGRAMMING KG College of Arts and Science
Loops are control structures used to repeat a given section of code a certain number of
times or until a particular condition is met.
Method #1: For loop
#list of items
list = ['M','R','C','E','T']
i=1
#Iterating over the list
for item in list:
print ('college ',i,' is ',item) i = i+1
Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/lis.py college 1 is M
college 2 is R college 3 is C college 4 is E college 5 is T
Method #2: For loop and range()
In case we want to use the traditional for loop which iterates from number x to number y.
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]
# getting length of list length = len(list)
# Iterating the index
# same as 'for i in range(len(list))' for i in range(length):
print(list[i])
Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/listlooop.py 1
3
5
7
9
Method #3: using while loop
# Python3 code to iterate over a list list = [1, 3, 5, 7, 9]
# Getting length of list
length = len(list) i = 0
# Iterating using while loop while i < length:
print(list[i]) i += 1
Mutability:
A mutable object can be changed after it is created, and an immutable object can't.
2.4 ALIASING:
1.An alias is a second name for a piece of data, often easier (and more useful) than making a
copy.

Page 47
PYTHON PROGRAMMING KG College of Arts and Science
2.If the data is immutable, aliases don‘t matter because the data can‘t change.
3.But if data can change, aliases can result in lot of hard – to – find bugs.
4.Aliasing happens whenever one variable‘s value is assigned to another variable.
For ex:
a = [81, 82, 83]
b = [81, 82, 83]
print(a == b)
print(a is b)
b=a
print(a == b)
print(a is b)
b[0] = 5
print(a)
Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/alia.py True
False True True
[5, 82, 83]
Because the same list has two different names, a and b, we say that it is aliased. Changes
made with one alias affect the other. In the example above, you can see that a and b refer to the
same list after executing the assignment statement b = a.
2.5 CLONING LISTS:
If we want to modify a list and also keep a copy of the original, we need to be able to
make a copy of the list itself, not just the reference. This process is sometimes called cloning, to
avoid the ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator. Taking any slice of a creates a
new list. In this case the slice happens to consist of the whole list.
Example:
a = [81, 82, 83]
b = a[:]
# make a clone using slice
print(a == b)
print(a is b)
b[0] = 5
print(a)
print(b)
Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/clo.py
True False
Page 48
PYTHON PROGRAMMING KG College of Arts and Science
[81, 82, 83]
[5, 82, 83]
Now we are free to make changes to b without worrying about a
2.5 List parameters:
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter change the
same list that the argument is referencing.
# for example, the function below takes a list as an argument and multiplies each element in the
list by 2:
def doubleStuff(List):
""" Overwrite each element in a List with double its value. """ for position in
range(len(List)):
List[position] = 2 * List[position]
things = [2, 5, 9] print(things) doubleStuff(things) print(things) Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/lipar.py == [2, 5, 9]
[4, 10, 18]
2.6 List comprehension:
List comprehensions provide a concise way to create lists. Common applications are to
make new lists where each element is the result of some operations applied to each member of
another sequence or iterable, or to create a subsequence of those elements that satisfy a certain
condition.
For example, assume we want to create a list of squares, like:
>>> list1=[]
>>> for x in range(10): list1.append(x**2)
>>> list1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
(or)
This is also equivalent to
>>> list1=list(map(lambda x:x**2, range(10)))
>>> list1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
(or)
Which is more concise and readable.
>>> list1=[x**2 for x in range(10)]
>>> list1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Similarly some examples:
>>> x=[m for m in range(8)]

Page 49
PYTHON PROGRAMMING KG College of Arts and Science
>>> print(x)
[0, 1, 2, 3, 4, 5, 6, 7]
>>> x=[z**2 for z in range(10) if z>4]
>>> print(x)
[25, 36, 49, 64, 81]
>>> x=[x ** 2 for x in range (1, 11) if x % 2 == 1]
>>> print(x)
[1, 9, 25, 49, 81]
>>> a=5
>>> table = [[a, b, a * b] for b in range(1, 11)]
>>> for i in table:
print(i)
[5, 1, 5]
[5, 2, 10]
[5, 3, 15]
[5, 4, 20]
[5, 5, 25]
[5, 6, 30]
[5, 7, 35]
[5, 8, 40]
[5, 9, 45]
[5, 10, 50]
2.7 TUPLES:
A tuple is a collection which is ordered and unchangeable. In Python tuples are written
with round brackets.
•Supports all operations for sequences.
•Immutable, but member objects may be mutable.
•If the contents of a list shouldn‘t change, use a tuple to prevent items from accidently being
added, changed, or deleted.
•Tuples are more efficient than list due to python‘s implementation.
We can construct tuple in many ways:
X=()
#no item tuple
X=(1,2,3)
X=tuple(list1) X=1,2,3,4
Example:
>>> x=(1,2,3)

Page 50
PYTHON PROGRAMMING KG College of Arts and Science
>>> print(x) (1, 2, 3)
>>> x (1, 2, 3)
>>> x=()
>>> x ()
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
Some of the operations of tuple are:
i)Access tuple items
ii)Change tuple items
iii)Loop through a tuple
iv)Count()
v)Index()
vi)Length()
i)Access tuple items:
Access tuple items by referring to the index number, inside square brackets
>>> x=('a','b','c','g')
>>> print(x[2]) c
ii) Change tuple items:
Once a tuple is created, you cannot change its values. Tuples are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module> x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same
iii) Loop through a tuple:
We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)

Page 51
PYTHON PROGRAMMING KG College of Arts and Science
4
5
6
7
2
aa
iv)Count ():
Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2) 4
v)Index ():
Searches the tuple for a specified value and returns the position of where it was found
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.index(2) 1
(Or)
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x.index(2)
>>> print(y) 1
vi)Length ():
To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y) 12
2.7.1 Tuple Assignment:
Python has tuple assignment feature which enables you to assign more than one variable
at a time. In here, we have assigned tuple 1 with the college information like college name, year,
etc. and another tuple 2 with the values in it like number (1, 2, 3… 7).
For Example, Here is the code,
>>> tup1 = ('KGCAS', 'eng college','2004','cse', 'it','csit');
>>> tup2 = (1,2,3,4,5,6,7);
>>> print(tup1[0])
KGCAS
>>> print(tup2[1:4])
(2, 3, 4)
Tuple 1 includes list of information of KGCAS
Tuple 2 includes list of numbers in it
We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4

Page 52
PYTHON PROGRAMMING KG College of Arts and Science
Run the above code- It gives name KGCAS for first tuple while for second tuple it gives number
(2, 3, 4)
2.7.2Tuple as return values:
A Tuple is a comma separated sequence of items. It is created with or without (). Tuples
are immutable.
# A Python program to return multiple values from a method using tuple
# This function returns a tuple def fun():
str = "KGCAS college" x = 20
return str, x; # Return tuple, we could also # write (str, x)
# Driver code to test above method str, x = fun() # Assign returned tuple print(str)
print(x)
Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/tupretval.py KGCAS college
20
2.7.3Functions can return tuples as return values.
def circleInfo(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14159 * r
a = 3.14159 * r * r return (c, a)
print(circleInfo(10))
Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/functupretval.py
(62.8318, 314.159)
def f(x):
y0 = x + 1 y1 = x * 3
y2 = y0 ** y3 return (y0, y1, y2)
2.7.4 Tuple comprehension:
Tuple Comprehensions are special: The result of a tuple comprehension is special. You
might expect it to produce a tuple, but what it does is produce a special "generator" object that
we can iterate over.
For example:
>>> x = (i for i in 'abc') #tuple comprehension
>>> x
<generator object <genexpr> at 0x033EEC30>
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a generator.
Page 53
PYTHON PROGRAMMING KG College of Arts and Science
The only thing that you need to know now about a generator now is that you can iterate over it,
but ONLY ONCE.
So, given the code
>>> x = (i for i in 'abc')
>>> for i in x:
print(i)
abc
Create a list of 2-tuples like (number, square):
>>> z=[(x, x**2) for x in range(6)]
>>> z
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
2.8 DICTIONARIES:
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
•Key-value pairs
•Unordered
We can construct or create dictionary like:
X={1:‘A‘,2:‘B‘,3:‘c‘}
X=dict([(‗a‘,3) (‗b‘,4)] X=dict(‗A‘=1,‘B‘ =2)
Example:
>>> dict1 = {"brand":"KGCAS","model":"college","year":2004}
>>> dict1
{'brand': 'KGCAS', 'model': 'college', 'year': 2004}
2.8.1 Operations and methods:
Methods that are available with dictionary are tabulated below. Some of them have
already been used in the above examples.

Method Description
clear() Remove all items form the dictionary.

copy() Return a shallow copy of the dictionary.

fromkeys(seq[, v]) Return a new dictionary with keys from seq and value
equal to v (defaults to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d
(defaults to None).
items() Return a new view of the dictionary's items (key, value).

keys() Return a new view of the dictionary's keys.

Page 54
PYTHON PROGRAMMING KG College of Arts and Science
pop(key[,d]) Remove the item with key and return its value or d if key
is not found. If d is not provided and key is not found,
raises KeyError.
popitem() Remove and return an arbitary item (key, value). Raises
KeyError if the dictionary is empty.
setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert
key with a value of d and return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from
other, overwriting existing keys.
values() Return a new view of the dictionary's values

Below are some dictionary operations:


To access specific value of a dictionary, we must pass its key,
>>> dict1 = {"brand":"KGCAS","model":"college","year":2004}
>>> x=dict1["brand"]
>>> x
'KGCAS'
To access keys and values and items of dictionary:
>>> dict1 = {"brand":"KGCAS","model":"college","year":2004}
>>> dict1.keys() dict_keys(['brand', 'model', 'year'])
>>> dict1.values() dict_values(['KGCAS', 'college', 2004])
>>> dict1.items()
dict_items([('brand', 'KGCAS'), ('model', 'college'), ('year', 2004)])
>>> for items in dict1.values(): print(items)
KGCAS college 2004
>>> for items in dict1.keys(): print(items)
brand model year
>>> for i in dict1.items():
print(i)
('brand', 'KGCAS')
('model', 'college')
('year', 2004)
Some more operations like:
i)Add/change
ii)Remove
iii)Length
iv)Delete
i)Add/change values:
Page 55
PYTHON PROGRAMMING KG College of Arts and Science
 can change the value of a specific item by referring to its key name
>>> dict1 = {"brand":"KGCAS","model":"college","year":2004}
>>> dict1["year"]=2005
>>> dict1
{'brand': 'KGCAS', 'model': 'college', 'year': 2005}
ii)Remove():
 It removes or pop the specific item of dictionary.
>>> dict1 = {"brand":"KGCAS","model":"college","year":2004}
>>> print(dict1.pop("model")) college
>>> dict1
{'brand': 'KGCAS', 'year': 2005}
iii)Delete:
 Deletes a particular item.
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> del x[5]
>>> x

iv)Length:
 use len() method to get the length of dictionary.
>>>{1: 1, 2: 4, 3: 9, 4: 16}
{1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y 4
2.8.2 Iterating over (key, value) pairs:
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> for key in x:
print(key, x[key])
11
24
39
4 16
5 25
>>> for k,v in x.items(): print(k,v)
11
24
39

Page 56
PYTHON PROGRAMMING KG College of Arts and Science
4 16
5 25
2.9 List of Dictionaries:
>>> customers = [{"uid":1,"name":"John"},
{"uid":2,"name":"Smith"},{"uid":3,"name":"Andersson"},
>>> >>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'Andersson'}]
## Print the uid and name of each customer
>>> for x in customers: print(x["uid"], x["name"])
1John
2Smith
3Andersson
## Modify an entry, This will change the name of customer 2 from Smith to Charlie
>>> customers[2]["name"]="charlie"
>>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'charlie'}] ## Add a new
field to each entry
>>> for x in customers:
x["password"]="123456" # any initial value
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 2, 'name': 'Smith', 'password': '123456'},
{'uid': 3, 'name': 'charlie', 'password': '123456'}]
## Delete a field
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 3, 'name': 'charlie', 'password': '123456'}]
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}] ## Delete all fields
>>> for x in customers: del x["uid"]
>>> x
{'name': 'John', 'password': '123456'}
2.9.1 Comprehension:
Dictionary comprehensions can be used to create dictionaries from arbitrary key and
value expressions:
>>> z={x: x**2 for x in (2,4,6)}
>>> z

Page 57
PYTHON PROGRAMMING KG College of Arts and Science
{2: 4, 4: 16, 6: 36}
>>> dict11 = {x: x*x for x in range(6)}
>>> dict11
{0: 0,1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

2.10 SETS:
 Sets are used to store multiple items in a single variable.

 unordered collection data type that is iterable, mutable and has no duplicate elements.

created by placing all the items (elements) inside curly braces {}, separated by comma, or by
using the built-in set() function
union of two sets that have some keys in common
a set must contain only one of each item, the union of two sets will contain only one of each key.
The null or empty set is a set with zero elements
Create with set()

 To create a set, you use the set() function or enclose one or more comma-separated
values in curly brackets, as shown here:
>>> empty_set = set() >>> empty_set set()

Convert from Other Data Types with set()

 Create a set from a list, string, tuple, or dictionary, discarding any duplicate values.
 >>> set( 'letters' ) {'l', 'e', 't', 'r', 's'}
 Now, let‘s make a set from a list:
 >>> set( ['Dasher', 'Dancer', 'Prancer', 'Mason-Dixon'] )
 {'Dancer', 'Dasher', 'Prancer', 'Mason-Dixon'}
Convert from Other Data Types with set()

 This time, a set from a tuple:


 >>> set( ('Ummagumma', 'Echoes', 'Atom Heart Mother') )
 {'Ummagumma', 'Atom Heart Mother', 'Echoes'}

 When you give set() a dictionary, it uses only the keys:


 >>> set( {'apple': 'red', 'orange': 'orange', 'cherry': 'red'} ) {'apple', 'cherry', 'orange'}
Test for Value by Using in

 This is the most common use of a set.


 make a dictionary called eatables.
 >>> eatables = {
... 'hot‘': {'tea', 'chocolate'},
... 'cold': {'chocolate', 'milkshake'},
... 'icecream': {'cream', 'chocolate', 'vanilla'},
... 'snacks': {'chips', 'pizza', 'chocolate'},
Page 58
PYTHON PROGRAMMING KG College of Arts and Science
... 'juices': {'milkshake', 'pineapple '}
... }
 Test for Value by Using in

 Even though both are enclosed by curly braces ({ and }),


 a set is just a sequence of values, and a dictionary is one or more key : value pairs.

Which drinks contain chocolate?

>>> for name, contents in eatables.items():


... if 'chocolate' in contents:
... print(name)
...

want something with chocolate but also milkshake

>>> for name, contents in drinks.items():


... if 'chocolate' in contents and not ('milkshake' in contents or
... 'cream' in contents):
... print(name)
...
Combinations and Operators

 use the set intersection operator, which is an ampersand (&)


 >>> for name, contents in drinks.items():
 ... if contents & {'milkshake', 'chocolate‘'}:
 ... print(name)
 ...
 The result of the & operator is a set, which contains all the items that appear in both lists
that you compare.
Set Operators
 >>> a = {1, 2}
 >>> b = {2, 3}

Intersection :
members common to both sets
symbol & or the set intersection() function
>>> a & b {2}
>>> a.intersection(b) {2}
union :
members of either set
using | or the set union() function
>>> a | b {1, 2, 3}
>>> a.union(b) {1, 2, 3}

difference :
members of the first set but not the second
using the character - or difference()
>>> a – b {1}
>>> a.difference(b) {1}
Page 59
PYTHON PROGRAMMING KG College of Arts and Science

exclusive or :
items in one set or the other, but not both
uses ^ or symmetric_difference()
>>> a ^ b {1, 3}
>>> a.symmetric_difference(b) {1, 3}

subset :
all members of the first set are also in the second set
using <= or issubset():
>>> a <= b False
>>> a.issubset(b) False

proper subset:
second set needs to have all the members of the first and more
Calculate it by using <,
>>> a < b False
>>> a < a
superset :
all members of the second set are also members of the first
uses >=or issuperset():
>>> a >= b False
>>> a.issuperset(b) False

proper superset :
the first set has all members of the second, and more
using >
>>> a > b
False

END OF UNIT II

Page 60
PYTHON PROGRAMMING KG College of Arts and Science

UNIT-III
FUNCTIONS: Definition - Passing parameters to a Function - Built-in functions- Variable
Number of Arguments - Scope – Type conversion-Type coercion-Passing Functions to a
Function - Mapping Functions in a Dictionary – Lambda - Modules - Standard Modules – sys –
math – time - dir - help Function.

3. FUNCTIONS
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for the application and a high degree of code
reusing. function is a group of related statements that performs a specific task. Functions helps to
break the program into smaller and modular chunks. One of the goodness of the function is code
reusable, more organized and manageable and avoids repetition. Python provides many built-in
functions like print(), etc. but can also create your own functions. These functions are called
user-defined functions.
3.1 Types of function
1)Built-in functions
min(),max(),sort(),print(),help() etc

2) User Defined Functions(UDFs)


users create the functions

3) Anonymous functions, which are also called lambda functions because they are not
declared with the standard def keyword.
3.1. Defining a Function:
Functions can be defined to provide the required functionality. Here are simple rules to define
a function in Python. Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).Any input parameters or arguments should be placed within these
parentheses. Parameters (if needed) can be defined inside these parentheses.The first statement
of a function can be an optional statement - the documentation string of the function or
docstring.
The code block within every function starts with a colon (:) and is indented. The statement
return [expression] exits a function, optionally passing back an expression to the caller. A return
statement with no arguments is the same as return None. Python functions don‘t have any
explicit begin or end like curly braces to indicate the start and stop for the function, they have to
Page 61
PYTHON PROGRAMMING KG College of Arts and Science
rely on this indentation.

Features of Function:
•Use the keyword def to declare the function and follow this up with the function name.
•Add parameters to the function: they should be within the parentheses of the function. End your
line with a colon.
•Add statements that the functions should execute.
•End your function with a return statement if the function should output something.
 Without the return statement, your function will return an object None.

Syntax :
def functionname( parameters ):
"function_docstring" function_suite
return [expression]
By default, parameters have a positional behavior and to inform them in the same order that
they were defined.
Example :
The following function takes a string as input parameter and prints it on standard screen.
def printme( str ):
"This prints a passed string into this function" print str
# Another Example
def hello():
print("Hello World")
return
3.1.1 Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code. Once the basic structure of a function is finalized, can
execute it by calling it from another function or directly from the Python prompt. Following is
the example to call printme() function
# Function definition is here def printme( str ):
"This prints a passed string into this function" print str
return;
# Now can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
When the above code is executed, it produces the following result −
I'm first call to user defined function! Again second call to the same function
3.1.3 How Function Return Value?
 Return command in Python specifies what value to give back to the caller of the function.

 functions immediately exit when they come across a return statement, even if it means
that they won‘t return any value

Creating Function with Return Statement


# Defining function
def sum():
a = 20
b = 40
c = a+b
return c
# calling sum() function in print statement

Page 62
PYTHON PROGRAMMING KG College of Arts and Science
print("The sum is given by:",sum())

#output
The sum is given by 60
Creating Function without Return Statement
# Defining function

def sum():
a = 20
b = 40
c = a+b
# calling sum() function in print statement
print(sum())
#output
None

3.1.2 PASSING PARAMETERS TO A FUNCTION


The function definition consists of the name, the parameters needed, the steps that will be carried
out by the function and returning values if any. A function in Python is called by using its name
followed by parentheses. In case parameters are present, these are included in the parentheses. A
function can take multiple arguments, these arguments can be objects, variables(of same or
different data types) and functions. Python functions are first class objects. It is possible to
define a function to receive one or more parameters (also called arguments) and use them for
processing inside the function block. Parameters/arguments may be given suitable formal
names. arguments are types of information that can be passed into the function. The arguments
are specified in the parentheses. Can pass any number of arguments to the functions, but have to
separate all the arguments with the help of a comma. Example : greet() function is now defined
to receive a string parameter called name. Inside the function, the print() statement is modified to
display the greeting message addressed to the received parameter.

# Example
 def greet(name):
 print ('Hello ', name)
 greet('students') # calling function with argument
 greet(123)

1)Passing parameters to a function - multiple parameters

# Defining the function for sum of two variables


def sum (num1,num2):
return num1+num2;
# Taking values from the user as an input
num1 = int(input("Enter the value of num1: "))
num2 = int(input("Enter the value of num2: "))
# Calculating and Printing the sum of num1 and num2
print("Sum = ",sum(num1,num2))

2)Parameter with Default Value

 While defining a function, its parameters may be assigned default values.

Page 63
PYTHON PROGRAMMING KG College of Arts and Science
 This default value gets substituted if an appropriate actual argument is passed when the
function is called.
 However, if the actual argument is not provided, the default value will be used inside the
function.
 The following greet() function is defined with the name parameter having the default
value 'Guest'.
 It will be replaced only if some actual argument is passed.
o def greet(name = 'Guest'):
print ('Hello', name)

greet()
greet('Steve')
 Output:
 Hello Guest
 Hello Steve

3.1.3 TYPES OF ARGUMENTS :


Python functions can contain two types of arguments:
o positional arguments and
o keyword arguments.
 Positional arguments must be included in the correct order.
 Keyword arguments are included with a keyword and equals sign.
i)Positional arguments :
 An argument is a variable, value or object passed to a function or method as input.
 Positional arguments are arguments that need to be included in the proper position or
order.
 The first positional argument always needs to be listed first when the function is called.
 The second positional argument needs to be listed second and the third positional
argument listed third, etc.
#Positional arguments are declared by a name only.
# Positional-Only argument
def functio(a, b, c, d, e, f):
print (a, b, c, d, e, f)

functio(1, 2, 3, d = 4, e = 5, f = 6) # It works fine


functio(a = 1, 2, a = 4, b = 5, c = 6) # Error occurred
ii)Function with Keyword Arguments(named arguments)
 In order to call a function with arguments, the same number of actual arguments must be
provided.
 However, a function can be called by passing parameter values using the parameter
names in any order.
 def greet(firstname, lastname):
print ('Hello', firstname, lastname)

 greet(lastname='Jobs', firstname='Steve')
 # passing parameters in any order using keyword argument
Page 64
PYTHON PROGRAMMING KG College of Arts and Science
#Output:
Hello Steve Jobs
a)Keyword Argument **kwarg
 The function can have a single parameter prefixed with **.
 This type of parameter initialized to a new ordered mapping receiving any excess
keyword arguments, defaulting to a new empty mapping of the same type.
 def greet(**person):
print('Hello ', person['firstname'], person['lastname'])

 greet(firstname='Steve', lastname='Jobs')
 greet(lastname='Jobs', firstname='Steve')
 greet(firstname='Bill', lastname='Gates', age=55)
 greet(firstname='Bill') # raises KeyError
#Output:
Hello Steve Jobs
Hello Steve Jobs
Hello Bill Gates
Error

3.1.4 Positional Vs Keyword Arguments


Positional Keyword
Positional arguments are declared by a name Keyword arguments are declared by a
only. name and a default value.
When a function is called, values for positional If we do not specify the value for a
arguments must be given. Otherwise, we will keyword argument, it takes the default
get an error. value.
Based on the position of arguments Based on the keywords arguments

Order /Position need to be followed Keywords can be in any order

iii)Unknown number of arguments/Arbitrary Arguments


 A function in Python can have an unknown number of arguments by putting * before the
parameter
 if you don't know the number of arguments the user is going to pass.
 def greet(*names):
print ('Hello ', names[0], ', ', names[1], ', ', names[3])

 greet('Steve', 'Bill', 'Yash')

3.2 PASSING FUNCTIONS TO A FUNCTION


 In Python, everything such as objects, variables, etc. is treated as an object.
 Therefore, functions/methods, are too treated as objects.
 A function can take multiple arguments, these arguments can be objects, variables(of
same or different data types) and functions.
 Python functions are first class objects. a function is assigned to a variable. This
assignment doesn‘t call the function.
 It takes the function object referenced by shout and creates a second name pointing to it,
yell.
 # Python program to illustrate functions

Page 65
PYTHON PROGRAMMING KG College of Arts and Science
 # can be treated as objects
 def shout(text):
 return text.upper()
 print(shout('Hello'))
 yell = shout
 print(yell('Hello'))
 #OUTPUT
 HELLO
 HELLO

Functions are first-class objects in python. you can pass them around, include them in dicts, lists,
etc. Just don't include the parenthesis after the function name.

#EXAMPLE:
def test ():
print "test was invoked"

def invoker(func):
func()
invoker(test) # prints test was invoked OUTPUT
test was invoked

3.2 BUILT IN FUNCTIONS


The Python built-in functions are defined as the functions whose functionality is pre-defined in
Python. The python interpreter has several functions that are always present for use. These
functions are known as Built-in Functions.

abs() - It returns the absolute value of a number, and the returned value is always positive.
all() – It returns true when all elements in an iterable are evaluated to be true orif there are no
elements in an iterable. It returns false if any element is evaluated to be false.
any() – It checks if any element of an iterable is true. Unlike all(), it returns false if there are no
elements in the iterable.

Page 66
PYTHON PROGRAMMING KG College of Arts and Science
ascii() – This method returns a string containing printable representation.
bin() -This built in function in Python is used for converting an integer to a binary string. bool()
– This built in function in Python is used for converting a value to Boolean.
bytearray() -This built in function in python returns an array of the given byte size. Python
bytes() – This built in function in Python returns immutable bytes object.
callable() – This built in function Python is used for checking if the object is callable.

#Example 1:
value = abs(-3.7)
print(value)
#Output: 3.7

#Example 2:
value = "Hello"
x = type(value)
print(x)

#Output:
< class str>

#Example 3:
value = [True, False, False]
check = any(value)
print(check)
Output : True

3.3 VARIABLE NUMBER OF ARGUMENTS


A variable length argument as the name suggests is an argument that can accept variable number
of values. To indicate that the function can take variable number of argument you write a
variable argument using a ‗*‘, for example *args.Variable arguments help in the scenario where
the exact number of arguments are not known in the beginning, it also helps to make your
function more flexible. Consider the scenario where you have a function to add numbers.

def add_num(num1, num2):


return num1 + num2

This function can only be used to add two numbers, if you pass more than two numbers you will
get an error.

result = add_num(5, 6, 7)
print('Sum is', result)
result = add_num(5, 6, 7)
TypeError: add_num() takes 2 positional arguments but 3 were given
By changing the argument to *args you can specify that function accepts variable number of
arguments and can be used to sum ‗n‘ numbers.
def add_num(*args):
sum = 0
for num in args: sum += num
return sum
result = add_num(5, 6, 7) print('Sum is', result)
result = add_num(5, 6, 7, 8) print('Sum is', result)
result = add_num(5, 6, 7, 8, 9) print('Sum is', result)
Page 67
PYTHON PROGRAMMING KG College of Arts and Science
#Output
Sum is 18
Sum is 26
Sum is 35

3.3.1 Points about variable length arguments in Python:-


 It is not mandatory to name variable length argument as ‗*args‘. What is required is *,
variable name can be any variable name for example *numbers, *names.
 Using variable length argument you can pass zero or more arguments to a function.
Values pass to *args are stored in a tuple.
 Before variable args you can have a formal argument but not after a variable args. After
variable argument you can have keyword arguments.

def add_num(n, *numbers):


sum = 0 print('n is', n)
for num in numbers:
sum += num
sum += n
return sum

#calling function
result = add_num(8, 5, 6, 7) print('Sum is', result)
#Output
n is 8
Sum is 26
i)As you can see here n is a formal argument and first value is passed to that argument.
ii)If you change the function to have a formal argument after the variable length argument-
def add_num(*numbers, n):
Then it results in an error.
#Output
result = add_num(8, 5, 6, 7)
TypeError: add_num() missing 1 required keyword-only argument: 'n' You can pass a keyword
argument after variable args.

def add_num(*numbers, n): sum = 0


print('n is', n)
for num in numbers: sum += num
sum += n return sum
#Calling function
result = add_num(5, 6, 7, n=8) print('Sum is', result)
#Output
n is 8

Sum is 26
3.3.2 Keyword variable length arguments in Python
Python keyword variable length argument is an argument that accept variable number of
keyword arguments (arguments in the form of key, value pair). To indicate that the function can
take keyword variable length argument you write an argument using double asterisk ‗**‘, for
example **kwargs. Values passed as keyword variable length argument are stored in a
dictionary that is referenced by the keyword arg name.
def display_records(**records):

Page 68
PYTHON PROGRAMMING KG College of Arts and Science
for k, v in records.items():
print('{} = {}'.format(k,v))
display_records(Firstname="Jack",Lastname="Douglas",marks1=45,marks2=42)
display_records(Firstname="Lisa",Lastname="Montana",marks1=48,marks2=45,marks3=49)
#Output
Firstname = Jack Lastname = Douglas marks1 = 45
marks2 = 42 Firstname = Lisa Lastname = Montana marks1 = 48
marks2 = 45
marks3 = 49
can pass a formal argument before a keyword variable length argument but not after that so
following is a valid function definition.
def display_records(a, **records):
3.4 SCOPE
The scope of a variable in python is that part of the code where it is visible.
1)Local Scope or Function Scope
•The local scope or function scope is a Python scope created at function calls. Every time user
call a function, it is also creating a new local scope.
•By default, parameters and names that assign inside a function exist only within the function or
local scope associated with the function call. When the function returns, the local scope is
destroyed and the names are forgotten.

#Example of Local Scope


•def myfunc():
x = 300
print(x)

myfunc()
2) GLOBAL SCOPE:
•A variable created in the main body of the Python code is a global variable and belongs to the
global scope.
•Global variables are available from within any scope, global and local.
#Example of Global Scope
x = 300
def myfunc():
print(x)
myfunc()
print(x)
2.1 GLOBAL KEYWORD
•Need to create a global variable, but are stuck in the local scope, can use the global keyword.
•The global keyword makes the variable global.
#Example
def myfunc():
global x x = 300
myfunc()
print(x)
3) BUILT IN SCOPE
•The built-in scope has all the names that are loaded into python variable scope when we start
the interpreter.
•For example, never need to import any module to access functions like print() and id().
•If a Variable is not defined in local, Enclosed or global scope, then python looks for it in the
built-in scope.
#Example
Page 69
PYTHON PROGRAMMING KG College of Arts and Science
# Built-in Scope from math import pi
def inner():
# pi = 'not defined in inner pi'
print(pi)
inner()
4)ENCLOSING SCOPE:
•Enclosing (or nonlocal) scope is a special scope that only exists for nested functions. If the local
scope is an inner or nested function, then the enclosing scope is the scope of the outer or
enclosing function. This scope contains the names that you define in the enclosing function. The
names in the enclosing scope are visible from the code of the inner and enclosing functions.
#Example
def red():
a=1
def blue():
print(―INNER BLOCK‖)
a=2
b=2
print(a)
print(b)

red()

blue()
print(―OUTER BLOCK‖,a)

3.5 TYPE CONVERSION:


•The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion. Python has two types of type conversion.
i)Implicit Type Conversion
ii)Explicit Type Conversion
i)IMPLICIT TYPE CONVERSION
•In Implicit type conversion, Python automatically converts one data type to another data type.
This process doesn't need any user involvement.
#EXAMPLE
num1= 123
num2 = 1.23
num_new = num1+ num2 print("datatype of num_int:",type(num1))
print("datatype of num_flo:",type(num2)) print("Value of num_new:",num_new) print("datatype
of num_new:",type(num_new))

#OUTPUT:
datatype of num_int: <class 'int'> datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
ii)EXPLICIT TYPE CONVERSION:
In Explicit Type Conversion, users convert the data type of an object to required data type. We
use the predefined functions like int(), float(), str(), etc to perform explicit type conversion.
•This type of conversion is also called typecasting because the user casts (changes) the data type
of the objects.
Syntax :
<required_datatype>(expression)
Page 70
PYTHON PROGRAMMING KG College of Arts and Science
#EXAMPLE:
num1= 123
num_new = num1+ num2 num3 =int(num_new) print(type(num3)) OUTPUT:
<class int>
3.5.1 PROPERTIES OF TYPE CONVERSION:
• Type Conversion is the conversion of object from one data type to another data type.
•Implicit Type Conversion is automatically performed by the Python interpreter.
•Python avoids the loss of data in Implicit Type Conversion.
•Explicit Type Conversion is also called Type Casting, the data types of objects are converted
using predefined functions by the user.
•In Type Casting, loss of data may occur as we enforce the object to a specific data type.
3.6 TYPE COERCION
•Python don't have type coercion. Python doesn't ever implicitly converts one object to another
type of object.
#EXAMPLE:
>>> name = "Trey"
>>> x 2
>>> name + x
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

numbers in Python don't know how to use the plus operator with strings, which means the code
doesn't work.
3.7 MAPPING FUNCTIONS IN A DICTIONARY
•Python map() function applies another function on a given iterable (List/String/Dictionary, etc.)
and returns map object. In simple words, it traverses the list, calls the function for each element,
and returns the results.
•Python map object is also iterable holding the list of each iteration. We can also convert it to
List or Dictionary or other types using their constructor functions.
 Python‘s map() is a built-in function that allows you to process and transform all the items in
an iterable without using an explicit for loop, a technique commonly known as mapping.
 map() is useful when need to apply a transformation function to each item in an iterable and
transform them into a new iterable.
 map() is one of the tools that support a functional programming style in Python.
•Python provides a function map() to transform the contents of given iterable sequence based on
logic provided by us i.e.
 map() takes a function object and an iterable (or multiple iterables) as arguments and returns an
iterator that yields transformed items on demand.
 The function‘s signature is defined as follows:
 map(function, iterable[, iterable1, iterable2,..., iterableN])
 function: A mandatory function to be given to map, that will be applied to all the items
available in the iterator.
 iterator: An iterable compulsory object. It can be a list, a tuple, etc. You can pass multiple
iterator objects to map() function.
 map() function takes two inputs as a function and an iterable object.
 The function that is given to map() is a normal function, and it will iterate over all the values
present in the iterable object given.
 For example, consider a list of numbers, and want to find the square of each of the numbers.
 The get the output, need an function that will return the square of the given number.

Page 71
PYTHON PROGRAMMING KG College of Arts and Science
#Ex : using loop
>>> numbers = [1, 2, 3, 4, 5]
>>> squared = []

>>> for num in numbers:


... squared.append(num ** 2)
...
>>> squared
[1, 4, 9, 16, 25]
#Ex : map() function
>>> def square(number):
... return number ** 2
...
>>> numbers = [1, 2, 3, 4, 5]
>>> squared = map(square, numbers)
>>> list(squared)
[1, 4, 9, 16, 25]
 square() is a transformation function that maps a number to its square value.
 call to map() applies square() to all of the values in numbers and returns an iterator that
yields square values.
 Then call list() on map() to create a list object containing the square values.
 # working of map. As list Return double of n
 def addition(n):
return n + n
# double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
A list in Python is a collection of objects that are put inside brackets ([ ]). Lists are more
flexible than sets since they can have duplicate objects.
 #map() as set
 def change_upper_case(s):
return str(s).upper()
chars = {'g', 'b', 'e', 'b', 'g'}
result = map(change_upper_case, chars)
print(set(result))

A set is an unordered sequence of items that you have to put inside braces ({ }). In a set,
you can't have duplicate items.

 Advantages of map () over loop :


Map()

 Since map() is written in C and is highly optimized, its internal implied


loop can be more efficient than a regular Python for loop.

Page 72
PYTHON PROGRAMMING KG College of Arts and Science
 A second advantage of using map() is related to memory consumption.
With a for loop, you need to store the whole list in your system‘s
memory. With map(), you get items on demand, and only one item is in
your system‘s memory at a given time.

3.8 LAMBDA FUNCTIONS


•A Lambda Function in Python programming is an anonymous function or a function having no
name. It is a small and restricted function having no more than one line. Just like a normal
function, a Lambda function can have multiple arguments with one expression.
•In Python, lambda expressions are utilized to construct anonymous functions. Every anonymous
function you define in Python will have 3 essential parts:
 The lambda keyword.
 The parameters (or bound variables), and
 The function body.

•A lambda function can have any number of parameters, but the function body can only contain
one expression. Moreover, a lambda is written in a single line of code and can also be invoked
immediately.
Syntax
•The formal syntax to write a lambda function is as given below:
lambda p1, p2: expression
•Here, p1 and p2 are the parameters which are passed to the lambda function. You can add as
many or few parameters as you need.
•However, notice that we do not use brackets around the parameters as we do with regular
functions.
•The last part (expression) is any valid python expression that operates on the parameters you
provide to the function.
Example:
adder = lambda x, y: x + y print (adder (1, 2))
# output:
3
#Example :
x="some kind of a useless lambda" (lambda x : print(x))(x)
The above one is valid
•Code Explanation
1.Here is the same string we defined in the previous example.
2.In this part, we are defining a lambda and calling it immediately by passing the string as an
argument.
#Example
#Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))

LAMBDA Advantages :
 The code is simple and clear.
 No additional variables are added.
 Differences Between Lambda Expressions And Named Functions:
 Can be passed immediately (without variables).
 Only one line of code can be included internally.
 Automatic return of results.

Page 73
PYTHON PROGRAMMING KG College of Arts and Science
 There is neither a document string nor a name.

Lambda Disadvantages :
i)Lambda expressions are a strange and unfamiliar syntax to many Python programmers.

ii)Lambda functions themselves lack names and documentation, meaning that the only way to
know what they do is to read the code.

iii)Lambda expressions can only contain one statement, so some readable language features,
such as tuple unpacking, cannot be used with them.

iv)Lambda functions can often be replaced with existing functions in the standard library or
Python built-in functions.
3.9 MODULES
•A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use. It also makes
the code logically organized.
# A simple module, calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)

•We can import the functions, classes defined in a module to another module using the import
statement in some other Python source file.
•Syntax:
import module
•When the interpreter encounters an import statement, it imports the module if the module is
present in the search path.
•A search path is a list of directories that the interpreter searches for importing a module.
•For example, to import the module calc.py, we need to put the following command at the top of
the script.
•Note: This does not import the functions or classes directly instead imports the module only. To
access the functions inside the module the dot(.) operator is used.
#Example:
# importing module calc.py import calc print(calc.add(10, 2)) Output:
12
i)Sys
The sys module in Python provides valuable information about the Python interpreter. You can
also use it to obtain details about the constants, functions and methods of the Python interpreter.
The sys module comes packaged with Python, which means you do not need to download and
install it separately using the PIP package manager.
In order to start using the sys module and its various functions, you need to import it. You can do
that using the below line of code,
import sys
Obtaining the list of arguments
In python, we can execute the script directly from our terminal using various arguments.
Sometimes it is nice to display the user the different arguments they‘ve used while executing the
script or to store it for other purposes.
We can achieve this with ease using the argv function present in the sys module. # Creating a
Python script named example.py
Page 74
PYTHON PROGRAMMING KG College of Arts and Science
import sys
print("You entered: ", sys.argv[1], sys.argv[2])
Now, if you run the above program through a terminal with arguments, we first change the
directory to the one where the script is present and then use,
python example.py Hello World
Typing the above line in the terminal will then execute the program which will then in turn print
out the arguments we‘ve entered.
Output Hello World
Note − In the above example we started with sys.argv[1] and not sys.argv[0], because
sys.argv[0] prints the name of script we are currently executing and not the argument provided.
Stopping the execution of the program
If you want to force quit the application or stop it from executing at any point, we can use the
exit() function within the sys module.
import sys print(―Hello there!‖) sys.exit()
print(―This line is not even executed because the program exited in the last line‖) Output
Hello there!
In the above example, we use the sys.exit() function to stop the execution of the program, thus
not printing the last line.
ii)math
•Python‘s from statement lets you import specific attributes from a module without importing
the module as a whole.
Example:
from math import sqrt, factorial print(sqrt(16))
print(factorial(6))
The above code imports sqrt() and factorial from the module math
#Output:
4.0
720
Import all Names – From import * Statement
•The * symbol used with the from import statement is used to import all the names from a
module to a current namespace.
Syntax:
from module_name import *
Example:
from math import * print(sqrt(16)) print(factorial(6))
Importing and renaming a module
We can rename the module while importing it using the as keyword.
Example:
import math as gfg print(gfg.sqrt(16)) print(gfg.factorial(6)) Output
4.0
720
iii)dir()
There is a built-in function to list all the function names (or variable names) in a module. The
dir() function:
Example :
List all the defined names belonging to the platform module: import platform
x = dir(platform) print(x)
iv)time
Time module in Python provides various time-related functions. This module comes under
Python‘s standard utility modules. time.time () method of Time module is used to get the time in
seconds since epoch. The handling of leap seconds is platform dependent.
Python has a module named time to handle time-related tasks. To use functions defined in the
Page 75
PYTHON PROGRAMMING KG College of Arts and Science
module, we need to import the module first. Here's how:
import time
Here are commonly used time-related functions.
Python time.time()
The time() function returns the number of seconds passed since epoch.
For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins).
import time
seconds = time.time()
print("Seconds since epoch =", seconds) Python time.ctime()
The time.ctime() function takes seconds passed since epoch as an argument and returns a string
representing local time.
import time
# seconds passed since epoch seconds = 1545925769.9618232
local_time = time.ctime(seconds) print("Local time:", local_time)
If you run the program, the output will be something like:
Local time: Thu Dec 27 15:49:29 2018 Python time.sleep()
The sleep() function suspends (delays) execution of the current thread for the given number of
seconds.
import time
print("This is printed immediately.") time.sleep(2.4)
print("This is printed after 2.4 seconds.")
iv)Python time.localtime()
The localtime() function takes the number of seconds passed since epoch as an argument and
returns struct_time in local time.
import time
result = time.localtime(1545925769) print("result:", result)
print("\nyear:", result.tm_year) print("tm_hour:", result.tm_hour)
When you run the program, the output will be something like:
result: time.struct_time(tm_year=2018, tm_mon=12, tm_mday=27, tm_hour=15, tm_min=49,
tm_sec=29, tm_wday=3, tm_yday=361, tm_isdst=0)
year: 2018
tm_hour: 15
If no argument or None is passed to localtime(), the value returned by time() is used.

v)Python time.gmtime()
The gmtime() function takes the number of seconds passed since epoch as an argument and
returns struct_time in UTC.
import time
result = time.gmtime(1545925769) print("result:", result) print("\nyear:", result.tm_year)
print("tm_hour:", result.tm_hour)
When you run the program, the output will be:
result = time.struct_time(tm_year=2018, tm_mon=12, tm_mday=28, tm_hour=8, tm_min=44,
tm_sec=4, tm_wday=4, tm_yday=362, tm_isdst=0)
year = 2018
tm_hour = 8
If no argument or None is passed to gmtime(), the value returned by time() is used.
vi)Python time.mktime()
The mktime() function takes struct_time (or a tuple containing 9 elements corresponding to
struct_time) as an argument and returns the seconds passed since epoch in local time. Basically,
it's the inverse function of localtime().
import time
t = (2018, 12, 28, 8, 44, 4, 4, 362, 0)
Page 76
PYTHON PROGRAMMING KG College of Arts and Science
local_time = time.mktime(t) print("Local time:", local_time)
3.10 HELP MODULE
Python help()
The help() method calls the built-in Python help system.
The syntax of help() is:
help(object) help() Parameters
The help() method takes a maximum of one parameter.
object (optional) - you want to generate the help of the given object How help() works in
Python?
The help() method is used for interactive use. It's recommended to try it in your interpreter when
you need help to write Python program and use Python modules.

Note: object is passed to help() (not a string) Try these on Python shell.
>>> help(list)
>>> help(dict)
>>> help(print)
>>> help([1, 2, 3])
If string is passed as an argument, name of a module, function, class, method, keyword, or
documentation topic, and a help page is printed.
Note: string is passed as an argument to help()
If string is passed as an argument, the given string is looked up as the name of a module,
function, class, method, keyword, or documentation topic, and a help page is printed.
>>> help('random thing')
>>> help('print')
>>> help('def')
>>> from math import * help('math.pow')
Note: no argument is passed to help()
If no argument is passed, Python's help utility (interactive help system) starts on the console.
>>> help()
Then, you can enter the name of the topic to get help on writing Python programs and using
Python modules. For example:
help> True help> 'print' help > print
To quit the help utility and return to the interpreter, you need to type quit and press enter. help >
quit

END OF UNIT-III

Page 77
PYTHON PROGRAMMING KG College of Arts and Science

UNIT- IV

ERROR HANDLING: Run Time Errors - Exception Model - Exception Hierarchy - Handling
Multiple Exceptions - Handling IO Exceptions .Data Streams - Access Modes Writing - Data to
a File Reading - Data From a File - Additional File Methods - Using Pipes as Data Streams -
Working with Directories.(11)

4.1 ERROR HANDLING :

There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.

4.1.1 Syntax Errors :

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint get
while the users who are still learning Python:

>>> while 1 print ‘Hello world‘


File "<stdin>", line 1, in ?
while 1 print ‘Hello world‘
^
SyntaxError: invalid syntax

The parser repeats the offending line and displays a little ‗arrow‘ pointing at the earliest point in
the line where the error was detected. The error is caused by (or at least detected at) the token
preceding the arrow: in the example, the error is detected at the keyword print, since a colon (‗:‘)
is missing before it. The file name and line number are printed so it is known where to look in
case the input came from a script.

4.1.2 Exceptions :

Even if a statement or expression is syntactically correct, it may cause an error when an


attempt is made to execute it. Errors detected during execution are called exceptions and are not
unconditionally fatal: can be handled them in Python programs. Most exceptions are not handled
by programs, however, and result in error messages as shown here:

>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo
>>> 4 + spam*3

Traceback (most recent call last):


File "<stdin>", line 1, in ?
NameError: name ‘spam‘ is not defined
>>> ‘2‘ + 2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: illegal argument type for built-in operation

Page 78
PYTHON PROGRAMMING KG College of Arts and Science
The last line of the error message indicates what happened. Exceptions come in different types,
and the type is printed as part of the message: the types in the example are ZeroDivisionError,
NameError and TypeError.
The string printed as the exception type is the name of the built-in name for the exception that
occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions
(although it is a useful convention). Standard exception names are built-in identifiers (not
reserved keywords). The rest of the line is a detail whose interpretation depends on the exception
type; its meaning is dependent on the exception type. The preceding part of the error message
shows the context where the exception happened, in the form of a stack backtrace. In general it
contains a stack backtrace listing source lines; however, it will not display lines read from
standard input.
The Python Library Reference lists the built-in exceptions and their meanings. The try and
except statements are used for handling exceptions

4.2 HANDLING I/O EXCEPTIONS :

It is possible to write programs that handle selected exceptions. Look at the following example,
which asks the user for input until a valid integer has been entered, but allows the user to
interrupt the program (using Control-C or whatever the operating system supports); note that a
user generated interruption is signalled by raising the KeyboardInterrupt exception.

>>> while 1:
... try:
... x= int(raw_input("Enter a number: "))
... break
... except ValueError:
... print "Not a valid number. Try again..."
...

The try statement works as follows.


 First, the try clause (the statement(s) between the try and except keywords) is executed.
 If no exception occurs, the except clause is skipped and execution of the try statement is
finished.
 If an exception occurs during execution of the try clause, the rest of the clause is skipped.
Then if its type matches the exception named after the except keyword, the rest of the try
clause is skipped, the except clause is executed, and then execution continues after the try
statement.
 If an exception occurs which does not match the exception named in the except clause, it
is passed on to outer try statements; if no handler is found, it is an unhandled exception
and execution stops with a message as shown above.

A try statement may have more than one except clause, to specify handlers for different
exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in
the corresponding try clause, not in other handlers of the same try statement. An except clause
may name multiple exceptions as a parenthesized list, for example:

... except (RuntimeError, TypeError, NameError):


... pass

The last except clause may omit the exception name(s), to serve as a wildcard. Use this with
extreme caution, since it is easy to mask a real programming error in this way! It can also be
used to print an error message and then re-raise the exception (allowing a caller to handle the
Page 79
PYTHON PROGRAMMING KG College of Arts and Science
exception as well):

import string, sys


try:
f = open(‘myfile.txt‘)
s = f.readline()
i = int(string.strip(s))
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise

The try ... except statement has an optional else clause, which, when present, must follow all
except clauses. It is useful for code that must be executed if the try clause does not raise an
exception. For example:

for arg in sys.argv[1:]:


try:
f = open(arg, ‘r‘)
except IOError:
print ‘cannot open‘, arg
else:
print arg, ‘has‘, len(f.readlines()), ‘lines‘
f.close()

The use of the else clause is better than adding additional code to the try clause because it avoids
accidentally catching an exception that wasn‘t raised by the code being protected by the try ...
except statement.
When an exception occurs, it may have an associated value, also known as the exception‘s
argument. The presence and type of the argument depend on the exception type. For exception
types which have an argument, the except clause may specify a variable after the exception name
(or list) to receive the argument‘s value, as follows:

>>> try:
... spam()
... except NameError, x:
... print ‘name‘, x, ‘undefined‘
...
name spam undefined

If an exception has an argument, it is printed as the last part (‗detail‘) of the message for
unhandled exceptions. Exception handlers don‘t just handle exceptions if they occur
immediately in the try clause, but also if they occur inside functions that are called (even
indirectly) in the try clause. For example:

>>> def this_fails():


... x= 1/0
...

Page 80
PYTHON PROGRAMMING KG College of Arts and Science
>>> try:
... this_fails()
... except ZeroDivisionError, detail:
... print ‘Handling run-time error:‘, detail
...

Handling run-time error: integer division or modulo :

To handle possible exceptions, use a try-except block:

try:
age = int(input("Please enter your age: "))
print("I see that you are %d years old." % age)
except ValueError:
print("Hey, that wasn't a number!")

 Python will try to process all the statements inside the try block.
 If a ValueError occurs at any point as it is executing them, the flow of control will
immediately pass to the except block, and any remaining statements in the try block will
be skipped.
 It is possible for one except clause to handle more than one kind of error: can provide a
tuple of exception types instead of a single type:

 try:
dividend = int(input("Please enter the dividend: "))
divisor = int(input("Please enter the divisor: "))
print("%d / %d = %f" % (dividend, divisor, dividend/divisor))
except(ValueError, ZeroDivisionError):
print("Oops, something went wrong!")

A try-except block can also have multiple except clauses.

 If an exception occurs, Python will check each except clause from the top down to see if
the exception type matches.
 If none of the except clauses match, the exception will be considered unhandled, and
your program will crash:

 try:
dividend = int(input("Please enter the dividend: "))
divisor = int(input("Please enter the divisor: "))
print("%d / %d = %f" % (dividend, divisor, dividend/divisor))
except ValueError:
print("The divisor and dividend have to be numbers!")
except ZeroDivisionError:
print("The dividend may not be zero!")
 *Note that in the example above if a ValueError occurs its known whether it was caused
by the dividend or the divisor not being an integer – either one of the input lines could
cause that error.
 To give the user more specific feedback about which input was wrong, will have to wrap
each input line in a separate try-except block:

Page 81
PYTHON PROGRAMMING KG College of Arts and Science
 try:
dividend = int(input("Please enter the dividend: "))
except ValueError:
print("The dividend has to be a number!")
try:
divisor = int(input("Please enter the divisor: "))
except ValueError:
print("The divisor has to be a number!")
try:
print("%d / %d = %f" % (dividend, divisor, dividend/divisor))
except ZeroDivisionError:
print("The dividend may not be zero!")

In general, it is a better idea to use exception handlers to protect small blocks of code against
specific errors than to wrap large blocks of code and write vague, generic error recovery code.It
may sometimes seem inefficient and verbose to write many small try-except statements instead
of a single catch-all statement, but we can mitigate this to some extent by making effective use
of loops and functions to reduce the amount of code duplication.

4.3 RAISING EXCEPTIONS :

The raise statement allows the programmer to force a specified exception to occur. For example:

>>> raise NameError, ‘HiThere‘


Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: HiThere

The first argument to raise names the exception to be raised. The optional second argument
specifies the exception‘s argument. To determine whether an exception was raised but don‘t
intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:

>>> try:
... raise NameError, ‘HiThere‘
... except NameError:
... print ‘An exception flew by!‘
... raise
...

An exception flew by!


Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere

4. 4 USER-DEFINED EXCEPTIONS

Programs may name their own exceptions by creating a new exception class. Exceptions should
typically be derived from the Exception class, either directly or indirectly. For example:

>>> class MyError(Exception):

Page 82
PYTHON PROGRAMMING KG College of Arts and Science
... def __init__(self, value):
... self.value = value
... def __str__(self):
... return ‗self.value‗
...
>>> try:
... raise MyError(2*2)
... except MyError, e:
... print ‘My exception occurred, value:‘, e.value
...
My exception occurred, value: 4
>>> raise MyError, ‘oops!‘
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: ‘oops!‘

Exception classes can be defined which do anything any other class can do, but are usually kept
simple, often only offering a number of attributes that allow information about the error to be
extracted by handlers for the exception. When creating a module which can raise several distinct
errors, a common practice is to create a base class for exceptions defined by that module, and
subclass that to create specific exception classes for different error conditions:

class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.

Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error

"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that‘s not allowed.

Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed

"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message

Most exceptions are defined with names that end in ―Error,‖ similar to the naming of the
standard exceptions. Many standard modules define their own exceptions to report errors that
Page 83
PYTHON PROGRAMMING KG College of Arts and Science
may occur in functions they define

4.4.1 Defining Clean-up Actions

The try statement has another optional clause which is intended to define clean-up actions that
must be executed under all circumstances. For example:

>>> try:
... raise KeyboardInterrupt
... finally:
... print ‘Goodbye, world!‘
...

Goodbye, world!

Traceback (most recent call last):


File "<stdin>", line 2, in ?
KeyboardInterrupt

A finally clause is executed whether or not an exception has occurred in the try clause. When an
exception has occurred, it is re-raised after the finally clause is executed. The finally clause is
also executed ―on the way out‖ when the try statement is left via a break or return statement.

The code in the finally clause is useful for releasing external resources (such as files or network
connections), regardless of whether or not the use of the resource was successful.A try statement
must either have one or more except clauses or one finally clause, but not both.

4.5 How an exception is handled


 When an exception occurs, the normal flow of execution is interrupted.
 Python checks to see if the line of code which caused the exception is inside a try block.
 If it is, it checks to see if any of the except blocks associated with the try block can
handle that type of exception.
 If an appropriate handler is found, the exception is handled, and the program continues
from the next statement after the end of that try-except.

 When a function is called, it is placed on Python‘s stack


 Python traverses this stack when it tries to handle an exception.
 If an exception is thrown by a line which is in the main body of your program, not inside
a function, the program will terminate.
 When the exception message is printed, should also see a traceback – a list which shows
the path the exception has taken, all the way back to the original line which caused the
error.
 There are two other clauses that can add to a try-except block:
 else and finally.
 else will be executed only if the try clause doesn‘t raise an exception:
 try:
Page 84
PYTHON PROGRAMMING KG College of Arts and Science
 age = int(input("Please enter your age: "))
 except ValueError:
 print("Hey, that wasn't a number!")
 else:
 print("I see that you are %d years old." % age)
 to print a message about the user‘s age only if the integer conversion succeeds.

 In the first exception handler example, put this print statement directly after the
conversion inside the try block.
 In both cases, the statement will only be executed if the conversion statement doesn‘t
raise an exception, but putting it in the else block is better practice – it means that the
only code inside the try block is the single line that is the potential source of the error that
we want to handle.
 When edit this program in the future, may introduce additional statements that should
also be executed if the age input is successfully converted.
 Some of these statements may also potentially raise a ValueError.
 If this is not noticed and put them inside the try clause, the except clause will also handle
these errors if they occur.
 This is likely to cause some odd and unexpected behaviour. By putting all this extra code
in the else clause instead, we avoid taking this risk.
 The finally clause will be executed at the end of the try-except block no matter what –if
there is no exception, if an exception is raised and handled, if an exception is raised and
not handled, and even if we exit the block using break, continue or return.
 can use the finally clause for cleanup code that we always want to be executed:

 try:
 age = int(input("Please enter your age: "))
 except ValueError:
 print("Hey, that wasn't a number!")
 else:
 print("I see that you are %d years old." % age)
 finally:
 print("It was really nice talking to you.Goodbye!")

To Summarise :
 raise allows you to throw an exception at any time.

 assert enables you to verify if a certain condition is met and throw an exception if it isn‘t.
 try clause, all statements are executed until an exception is encountered.
 except is used to catch and handle the exception(s) that are encountered in the try clause.
 else lets you code sections that should run only when no exceptions are encountered in
the try clause.
 finally enables you to execute sections of code that should always run, with or without
any previously encountered exceptions.

Page 85
PYTHON PROGRAMMING KG College of Arts and Science
4.5 EXCEPTION MODEL :

Four main components of exception handling:

 Try: It will run the code block in which you expect an error to occur.
 Except: Here, you will define the type of exception you expect in the try block (built-in
or custom).
 Else: If there isn't any exception, then this block of code will be executed (consider this
as a remedy or a fallback option if you expect a part of your script to produce an
exception).
 Finally: Irrespective of whether there is an exception or not, this block of code will
always be executed.

few important points in Exception Handling :


 A single try statement can have multiple except statements. This is useful when the try
block contains statements that may throw different types of exceptions.
 can also provide a generic except clause, which handles any exception.
 After the except clause(s), include an else-clause. The code in the else-block executes if
the code in the try: block does not raise an exception.
 else-block is a good place for code that does not need the try: block's protection.

 Python provides the number of built-in exceptions, but here we are describing the
common standard exceptions.
 A list of common exceptions that can be thrown from a standard Python program is given
below.
 ZeroDivisionError: Occurs when a number is divided by zero.
 NameError: It occurs when a name is not found. It may be local or global.
 IndentationError: If incorrect indentation is given.
Page 86
PYTHON PROGRAMMING KG College of Arts and Science
 IOError: It occurs when Input Output operation fails.
 EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
 All the runtime (and syntax) errors that encountered are called exceptions in Python –
 Python uses them to indicate that something exceptional has occurred, and that your
program cannot continue unless it is handled.
 All exceptions are subclasses of the Exception class –

4.6 EXCEPTION HIERARCHY IN PYTHON :

The Python exception class hierarchy consists of a few dozen different exceptions spread across
a handful of important base class types. As with most programming languages, errors occur
within a Python application when something unexpected goes wrong. Anything from improper
arithmetic and running out of memory to invalid file references and unicode formatting errors
may be raised by Python under certain circumstances.

Most of the errors we‘ll explore in this series are considered exceptions, which indicate that
these are non-fatal errors. While a fatal error will halt execution of the current application, all
non-fatal exceptions allow execution to continue. This allows our code to explicitly catch
or rescue the raised exception and programmatically react to it in an appropriate manner.

Page 87
PYTHON PROGRAMMING KG College of Arts and Science

4.6.1 EXCEPTION ERROR – TYPES :

Page 88
PYTHON PROGRAMMING KG College of Arts and Science

4.6.2 HIERARCHY FOR BASE EXCEPTION:

4.6.3 Major Exception Types Overview

These top-level exceptions will serve as a basis for digging into specific exceptions in future
articles.

o BaseException
o Exception
 ArithmeticError

Page 89
PYTHON PROGRAMMING KG College of Arts and Science
 FloatingPointError
 OverflowError
 ZeroDivisionError
 AssertionError

Distinction between using the word exception in the BaseException and Exception parent
classes, and the use of error in most subclasses therein. Most other languages, such as .NET or
Java, explicitly differentiate between exceptions and errors by separating them into distinct
categories. In such languages, errors typically denote fatal errors (those that crash the
application), whereas exceptions are catchable/rescuable errors.

i)BaseException

The BaseException class is, as the name suggests, the base class for all built-in exceptions in
Python. Typically, this exception is never raised on its own, and should instead be inherited by
other, lesser exception classes that can be raised.

The BaseException class (and, thus, all subclass exceptions as well) allows a tuple of
arguments to be passed when creating a new instance of the class. In most cases, a single
argument will be passed to an exception, which is a string value indicating the specific error
message.

This class also includes a with_traceback(tb) method, which explicitly sets the new traceback
information to the tb argument that was passed to it.

ii)Exception

Exception is the most commonly-inherited exception type (outside of the true base class
of BaseException). In addition, all exception classes that are considered errors are subclasses of
the Exception class. In general, any custom exception class create in our own code should
inherit from Exception. The Exception class contains many direct child subclasses that handle
most Python errors, so it is briefly explained below:

 ArithmeticError – The base class for the variety of arithmetic errors, such as when
attempting to divide by zero, or when an arithmetic result would be too large for Python to
accurately represent.
 AssertionError – This error is raised when a call to the [assert] statement fails.
 AttributeError – Python‘s syntax includes something called attribute
references, which is just the Python way of describing what might know of as dot
notation. In essence, any primary token in Python (like an identifier, literal,
and so forth) can be written and followed by a period (.), which is then followed by
an identifier. That syntax (i.e. primary.identifier) is called an attribute
reference, and anytime the executing script encounters an error in such syntax
an AttributeError is raised.
 BufferError – Python allows applications to access low level memory streams in the form
of a buffer. For example, the bytes class can be used to directly work with bytes of
information via a memory buffer. When something goes wrong within such a buffer operation
a BufferError is raised.

Page 90
PYTHON PROGRAMMING KG College of Arts and Science
 EOFError – Similar to the Java EOFException article we did a few days ago,
Python‘s EOFError is raised when using the input() function and reaching the end of a file
without any data.
 ImportError – Modules are usually loaded in memory for Python scripts to use via
the import statement (e.g. import car from vehicles). However, if
an import attempt fails an ImportError will often be raised.
 LookupError – Like ArithmeticError, the LookupError is generally considered a
base class from which other subclasses should inherit. All LookupError subclasses deal with
improper calls to a collection are made by using invalid key or index values.
 MemoryError – In the event that Python application is about to run out of memory
a MemoryError will be raised. Since Python is smart enough to detect this potential
issue slightly before all memory is used up, a MemoryError can be rescued and allow you
to recover from the situation by performing garbage collection of some kind.
 NameError – Raised when trying to use an identifier with an invalid or unknown name.
 OSError – This error is raised when a system-level problem occurs, such as failing to find a
local file on disk or running out of disk space entirely. OSError is a parent class to many
subclasses explicitly used for certain issues related to operating system failure, so we‘ll explore
those in future publications.
 ReferenceError – Python includes the weakref module, which allows Python code to
create a specific type of reference known as a weak reference. A weak reference is a
reference that is not ―strong‖ enough to keep the referenced object alive. This means that the
next cycle of garbage collection will identify the weakly referenced object as no longer strongly
referenced by another object, causing the weakly referenced object to be destroyed to free up
resources. If a weak reference proxy created via the weakref.proxy() function is
used after the object that is referenced has already been destroyed via garbage collection,
a ReferenceError will be raised.
 RuntimeError – A RuntimeError is typically used as a catchall for when an error
occurs that doesn‘t really fit into any other specific error classification.
 StopIteration – If no default value is passed to the next() function when iterating
over a collection, and that collection has no more iterated value to retrieve,
a StopIteration exception is raised. Note that this is not classified as an Error, since it
doesn‘t mean that an error has occurred.
 StopAsyncIteration – As of version 3.5, Python now includes coroutines for
asynchronous transactions using the async and await syntax. As part of this feature,
collections can be asynchronously iterated using the __anext__() method.
The __anext__() method requires that a StopAsyncIteration instance be raised in
order to halt async iteration.
 SyntaxError – Just like most programming languages, a SyntaxError in Python
indicates that there is some improper syntax somewhere in your script file.
A SyntaxError can be raised directly from an executing script, or produced via functions
like eval() and exec().
 SystemError – A generic error that is raised when something goes wrong with the Python
interpreter (not to be confused with the OSError, which handles operating system issues).
 TypeError – This error is raised when attempting to perform an operation on an incorrect
object type.
 ValueError – Should be raised when a function or method receives an argument of the
correct type, but with an actual value that is invalid for some reason.

Page 91
PYTHON PROGRAMMING KG College of Arts and Science
 Warning – Another parent class to many subclasses, the Warning class is used to alert the
user in non-dire situations. There are a number of subclass warnings that we‘ll explore in future
articles.

GeneratorExit

A generator is a specific type of iterator in Python, which simplifies the process of creating
iterators with constantly changing values. By using the yield statement within a generator code
block, Python will return or ―generate‖ a new value for each call to next(). When the
explicit generator.close() method is called a GeneratorExit instance is raised.

KeyboardInterrupt

This simple exception is raised when the user presses a key combination that causes
an interrupt to the executing script. For example, many terminals accept Ctrl+C as an
interrupt keystroke.

SystemExit

Finally, the SystemExit exception is raised when calling the sys.exit() method, which
explicitly closes down the executing script and exits Python. Since this is an exception, it can
be rescued and programmatically responded to immediately before the script actually shuts
down.

4. 7 DATA STREAMS :
Data streams are continuous flows of data. Examples of data streams include network
traffic, sensor data, call center records and so on. Also known as event stream processing,
streaming data is the continuous flow of data generated by various sources. By using stream
processing technology, data streams can be processed, stored, analyzed, and acted upon as it's
generated in real-time. The term "streaming" is used to describe continuous, never-ending data
streams with no beginning or end, that provide a constant feed of data that can be utilized/acted
upon without needing to be downloaded first.
Similarly, data streams are generated by all types of sources, in various formats and
volumes. From applications, networking devices, and server log files, to website activity,
banking transactions, and location data, they can all be aggregated to seamlessly gather real-time
information and analytics from a single source of truth.

Examples :
Some real-life examples of streaming data include use cases in every industry, including real-
time stock trades, up-to-the-minute retail inventory management, social media feeds, multiplayer
game interactions, and ride-sharing apps.
For example, when a passenger calls Lyft, real-time streams of data join together to create a
seamless user experience. Through this data, the application pieces together real-time location
tracking, traffic stats, pricing, and real-time traffic data to simultaneously match the rider with
the best possible driver, calculate pricing, and estimate time to destination based on both real-
time and historical data.
In this sense, streaming data is the first step for any data-driven organization, fueling big data
ingestion, integration, and real-time analytics.

A data stream is where the data is available instantly as and when an event occurs. It can

Page 92
PYTHON PROGRAMMING KG College of Arts and Science
be real-time or near real-time. Instead of collecting and storing data from events overtime and
then shipping the file to an application, the data is available to the application as and when the
event occurs. i.e., a credit card transaction has to be instant — the available credit has to be
updated instantly after a transaction. It cannot wait for an overnight batch rerun as the available
credit displayed to the consumer might not be accurate and leads to a lot of confusion due to
transaction duplication.

Kafka is a distributed publish-subscribe messaging system (incubated at Linkedin). It is used


to handle high-throughput messaging applications like clicks on web pages, log aggregations, and
stream processing. Three important keywords in Kafka will be a producer (publisher), consumer
(subscribers), and topic. The system is comparable to an infinite magnetic tape spool. An
application can write to Kafka real-time as and when the events occur (publish messages to
stream), and another application can read from the tape from a given offset (consume
messages from the stream).
Multiple data streams can co-exist in Kafka messaging environment they are distinguished
between each other by their topic name. i.e., Youtube will be the best example. Viewers can
subscribe to a channel (topic). Channel owner (producer) can push new content (event) to a
channel. Subscribers (consumers) receives the notification of new content. A channel owner can
run multiple channels. A channel can have a lot of subscribers. A subscriber can subscribe to
various channels.
RabbitMQ, Google PubSub, Amazon Kinesis Stream, Wallaroo, and Redis Streams are few
alternatives to Kafka.

4.7.1 Batch Processing vs Real-Time Streams :


Batch data processing methods require data to be downloaded as batches before it can be
processed, stored, or analyzed, whereas streaming data flows in continuously, allowing that data
to be processed simultaneously, in real-time the second it's generated.
Today, data arrives naturally as never ending streams of events. This data comes in all volumes,
formats, from various locations and cloud, on-premises, or hybrid cloud.
With the complexity of today's modern requirements, legacy data processing methods have
Page 93
PYTHON PROGRAMMING KG College of Arts and Science
become obsolete for most use cases, as it can only process data as groups of transactions
collected over time. Modern organizations need to act on up-to-the-millisecond data, before the
data becomes stale. This continuous data offers numerous advantages that are transforming the
way businesses run.

4.7.2 Benefits of Streaming Data :


Data collection is only one piece of the puzzle. Today‘s enterprise businesses simply cannot wait
for data to be processed in batch form. Instead, everything from fraud detection and stock market
platforms, to ride share apps and e-commerce websites rely on real-time data streams.
Paired with streaming data, applications evolve to not only integrate data, but process, filter,
analyze, and react to that data in real-time, as it's received. This opens a new plethora of use
cases such as real-time fraud detection, Netflix recommendations, or a seamless shopping
experience across multiple devices that updates as you shop.
In short, any industry that deals with big data, can benefit from continuous, real-time data will
benefit from this technology.
4.7.3 Use Cases:
Stream processing systems like Apache Kafka bring real-time data and analytics to life. While
there are use cases for data streaming in every industry, this ability to integrate, analyze,
troubleshoot, and/or predict data in real-time, at massive scale, opens up new use cases. Not only
can organizations use past data or batch data in storage, but gain valuable insights on data in
motion.
4.7.3.1 Typical uses cases include:
 Location data
 Fraud detection
 Real-time stock trades
 Marketing, sales, and business analytics
 Customer/user activity
 Monitoring and reporting on internal IT systems
 Log Monitoring: Troubleshooting systems, servers, devices, and more
 SIEM (Security Information and Event Management)-analyzing logs and real time
event data for monitoring, metrics, and threat detection
 Retail/warehouse inventory: inventory management across all channels and
locations, and providing a seamless user experience across all devices
 Ride share matching: Combining location, user, and pricing data for predictive
analytics - matching riders with the best drivers in term of proximity, destination,
pricing, and wait times
 Machine learning and A.I.: By combining past and present data for one central
nervous system,
 predictive analytics bring new possibilities.

As long as there is any type of data to be processed, stored, or analyzed, a stream processing
system like Apache Kafka can help leverage your data to produce numerous use cases. It's open
source software that anyone can use for free.

Page 94
PYTHON PROGRAMMING KG College of Arts and Science

4.8 FILE HANDLING Or FILE ORGANISATION :

Files are named locations on disk to store related information. They are 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 the computer is turned off), use files for future use of the data
by permanently storing them. To read from or write to a file, need to open it first. When it is
done, it needs to be closed so that the resources that are tied with the file are freed.Hence, in
Python, a file operation takes place in the following order:

1. Open a file
2. Read or write (perform operation)
3. Close the file

1. Opening Files in Python :


Python has a built-in open() function 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.
# Example :
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python38/README.txt") # specifying full path
The mode while opening a file is specified. In mode, specify whether to read ‗r‘, write ‗w‘ or
append ‗a‘ to the file. To open the file in text mode or binary mode can also be mentioned.
2. Reading or Writing the Files :
The default is reading in text mode. In this mode, strings are received when reading from
the file.On the other hand, binary mode returns bytes and this is the mode to be used when
dealing with non-text files like images or executable files.
Mode Description
r Opens a file for reading. (default)
w Opens a file for writing. Creates a new file if it does
not exist or truncates the file if it exists.
x Opens a file for exclusive creation. If the file already
exists, the operation fails.
a Opens a file for appending at the end of the file without
truncating it. Creates a new file if it does not exist.
t Opens in text mode. (default)
b Opens in binary mode.
+ Opens a file for updating (reading and writing)

# Example with modes


>>>f = open("test.txt") # equivalent to 'r' or 'rt'
>>>f = open("test.txt",'w') # write in text mode
>>>f = open("img.bmp",'r+b') # read and write in binary mode

Unlike other languages, the character a does not imply the number 97 until it is encoded using
ASCII (or other equivalent encodings).Moreover, the default encoding is platform dependent. In
windows, it is cp1252 but utf-8 in Linux. So, it should not be relayed on the default encoding or
else our code will behave differently in different platforms.
Hence, when working with files in text mode, it is highly recommended to specify the encoding

Page 95
PYTHON PROGRAMMING KG College of Arts and Science
type.
>>>f = open("test.txt", mode='r', encoding='utf-8')

3. Closing Files in Python :


When done with performing operations on the file, need to properly close the file. Closing a file
will free up the resources that were tied with the file. It is done using the close() method
available in Python.Python has a garbage collector to clean up unreferenced objects but must not
rely on it to close the file.

#Example
>>> f = open("test.txt", encoding = 'utf-8')
# perform file operations
>>>f.close()
This method is not entirely safe. If an exception occurs when it is performing some operation
with the file, the code exits without closing the file.A safer way is to use a try...finally block.

>>>try:
f = open("test.txt", encoding = 'utf-8')
# perform file operations
finally:
f.close()
This way, it‘s guaranteed that the file is properly closed even if an exception is raised that causes
program flow to stop. The best way to close a file is by using the with statement. This ensures
that the file is closed when the block inside the with statement is exited. There is no need to
explicitly call the close() method. It is done internally.
with open("test.txt", encoding = 'utf-8') as f:

4.9 PERFORM FILE OPERATIONS


4.9.1 Python Methods - Writing to Files in Python :
In order to write into a file in Python, need to open it in write ‗w‘, append ‗a‘ or exclusive
creation ‗x‘ mode. Need to be careful with the w mode, as it will overwrite into the file if it
already exists. Due to this, all the previous data are erased. Writing a string or sequence of bytes
(for binary files) is done using the write() method. This method returns the number of characters
written to the file.
>>>with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
This program will create a new file named test.txt in the current directory if it does not exist. If it
does exist, it is overwritten. Must include the newline characters ourselves to distinguish the
different lines.

2. Reading Files in Python


To read a file in Python, must open the file in reading ‗r‘ mode.There are various methods
available for this purpose. Use the read(size) method to read in the size number of data. If the
size parameter is not specified, it reads and returns up to the end of the file.
Read the text.txt file in the following way:
>>> f = open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4) # read the first 4 data
'This'
>>> f.read(4) # read the next 4 data
' is '
Page 96
PYTHON PROGRAMMING KG College of Arts and Science
>>> f.read() # read in the rest till end of file
'my first file\nThis file\ncontains three lines\n'
>>> f.read() # further reading returns empty sting
''
read() method returns a newline as '\n'. Once the end of the file is reached, get an empty string
on further reading. Can change the current file cursor (position) using the seek() method.
Similarly, the tell() method returns current position (in number of bytes).
>>> f.tell() # get the current file position
56
>>> f.seek(0) # bring file cursor to initial position
0
>>> print(f.read()) # read the entire file
This is my first file
This file
contains three lines

can read a file line-by-line using a for loop. This is both efficient and fast.

>>> for line in f:


... print(line, end = '')
...
This is my first file
This file
contains three lines

In this program, the lines in the file itself include a newline character \n. So, use the end
parameter of the print() function to avoid two newlines when printing.Alternatively, can use the
readline() method to read individual lines of a file. This method reads a file till the newline,
including the newline character.

>>> f.readline()
'This is my first file\n'
>>> f.readline()
'This file\n'
>>> f.readline()
'contains three lines\n'
>>> f.readline()
''
Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading
methods return empty values when the end of file (EOF) is reached.
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']

Page 97
PYTHON PROGRAMMING KG College of Arts and Science

4.9.2 PYTHON FILE METHODS :


There are various methods available with the file object. Some of them have been used in the
above examples.Here is the complete list of methods in text mode with a brief description:
Method Description
close() Closes an opened file. It has no effect if the file is
already closed.
detach() Separates the underlying binary buffer from the
TextIOBase and returns it.
fileno() Returns an integer number (file descriptor) of the file.
flush() Flushes the write buffer of the file stream.
isatty() Returns True if the file stream is interactive.
read(n) Reads at most n characters from the file. Reads till end
of file if it is negative or None.
readable() Returns True if the file stream can be read from.
readline(n=-1) Reads and returns one line from the file. Reads in at
most n bytes if specified.
readlines(n=-1) Reads and returns a list of lines from the file. Reads in
at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Changes the file position to offset bytes, in reference to
from (start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
truncate(size=None) Resizes the file stream to size bytes. If size is not
specified, resizes to current location.
writable() Returns True if the file stream can be written to.
write(s) Writes the string s to the file and returns the number of
characters written.
writelines(lines) Writes a list of lines to the file.

Some Examples:
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
print ("Closed or not : ", fo.closed)
print ("Opening mode : ", fo.mode)
print ("Softspace flag : ", fo.softspace)
1. File close() Method :

The close() method closes an open file.Should always close your files, in some cases, due to
buffering, changes made to a file may not show until you close the file.

Syntax
file.close()
2. fileno() method
fileno() method is an inbuilt method in python, which returns the file descriptor of the stream as
a number. An error can occur if the operating system does not use a file descriptor.

Syntax

Page 98
PYTHON PROGRAMMING KG College of Arts and Science
file.fileno()
Example:
myfile = open("example.txt", "r")
print(myfile.fileno())
Here, when it print “myfile
Here, when it print “myfile.fileno()” then the output will appear “ 3 ”. Also, fileno() returns an
integer value which is the file descriptor.

The fileno() method returns the file descriptor of the stream, as a number. An error will occur
if the operator system does not use a file descriptor. Return the file descriptor of the stream.

f = open("demofile.txt", "r")
print(f.fileno())
3.flush() Method

The flush() method cleans out the internal buffer.

Syntax
file.flush()
Example
can clear the buffer when writing to a file:
f = open("myfile.txt", "a")
f.write("Now the file has one more line!")
f.flush()
f.write("...and another one!")

4. isatty() :

The isatty() method returns True if the file stream is interactive, example: connected to a
terminal device.

Syntax
file.isatty()
Example:
Check if the file is connected to a terminal device:
f = open("demofile.txt", "r")
print(f.isatty())

4. read() :

The read() method returns the specified number of bytes from the file. Default is -1 which
means the whole file.

Syntax
file.read()
Example:

Page 99
PYTHON PROGRAMMING KG College of Arts and Science
f = open("demofile.txt", "r")
print(f.read())
Parameter Values

Parameter Description

Size Optional. The number of bytes to return. Default -1, which means
the whole file.

More examples:
Example
Read the content of the file "demofile.txt":
f = open("demofile.txt", "r")
print(f.read(33))

6. readable()

The readable() method returns True if the file is readable, False if not.

Syntax
file.readable()
#Example
#Check if the file is readable:
f = open("demofile.txt", "r")
print(f.readable())

7.readlines()

readlines() method returns a list containing each line in the file as a list item.The Python
file readline() method reads one entire first line from the “examplefile.txt” file. By using the
size parameter we can get the specified bytes in output.

Syntax
file.readlines(hint)

#Example:
f = open("examplefile.txt", "r")
print(f.readline())

Here, when we will print “f.readline()” then the output will appear “Hello all! Welcome to file
examples.”. Also, can see that the readline() returns the first line from the file. Can also specify
how many bytes from the line to return.

Page 100
PYTHON PROGRAMMING KG College of Arts and Science
#Example 2
f = open("demofile.txt", "r")
print(f.readlines())

Use the hint parameter to limit the number of lines returned. If the total number of bytes returned
exceeds the specified number, no more lines are returned.

Parameter Values
Parameter Description

hint Optional. If the number of bytes returned exceed the hint number, no more lines
will be returned. Default value is -1, which means all lines will be returned.

#More examples
#Example
Do not return the next line if the total number of returned bytes are more than 33:
f= open("demofile.txt", "r")
print(f.readlines(33))
seek()
8. seek() Method

The seek() method sets the current file position in a file stream and also returns the new postion.

Syntax
file.seek(offset)
Parameter Values
Parameter Description
Offset Required. A number representing the position to set the
current file stream position.
#More examples
# Example

Change the current file position to 4, and return the rest of the line:

f = open("demofile.txt", "r")
f.seek(4)
print(f.readline())

#Example
#Return the new position:
f= open("demofile.txt", "r")
print(f.seek(4))

9. seekable() Method

Page 101
PYTHON PROGRAMMING KG College of Arts and Science
The seekable() method returns True if the file is seekable, False if not.A file is seekable if it
allows access to the file stream, like the seek() method.

Syntax
file.seekable()
Parameter Values

No parameters.

10. tell() Method

The tell() method returns the current file position in a file stream. can change the current file
position with the seek() method.

Syntax
file.tell()
Parameter Values

No parameter values.

#Example
#Find the current file position:
f = open("demofile.txt", "r")
print(f.tell())
#More examples
# Example
# Return the current file position after reading the first line:
f = open("demofile.txt", "r")
print(f.readline())
print(f.tell())

11.file writable() method


The Python file writable() method is an inbuilt method that returns True if the file is writable
otherwise it will return False if the file is not writable. A file is writable only if it‘s opened
using “w” for write and “a” for append.
#Example:
myfile = open("examplefile.txt", "w")
print(myfile.writable())
myfile.close()
To get the output we will print “myfile.writable()” it will return the boolean
value “True” which means the file is writable and the file is opened using “w”.

12. file readable() method:


The readable() method in Python is an inbuilt method in python, it checks whether a file is
readable or not. This method returns a boolean value. The readable() method returns True if the
file is readable otherwise it will return False.
#Example:
Page 102
PYTHON PROGRAMMING KG College of Arts and Science
myfile = open("examplefile.txt", "r")
print(myfile.readable())
myfile.close()
To get the output we will print “myfile.readable()” and it will return “True” as an output
because the file is readable. A file is readable if it‘s opened using “r”.

13.file truncate() method:


The truncate() method in Python file, is an inbuilt method in python, it resizes the file to a given
number of bytes. open the file in “w” mode and then write on the file. Here, given the size as
“25” which is an optional parameter.After the truncate method, will read the file, and print
―myfile.read()‖ to see the output.
#Example:
myfile = open("examplefile.txt", "w")
myfile.write("Python is one of the good programming language")
myfile.truncate(25)
myfile.close()
myfile = open("examplefile.txt", "r")
print(myfile.read())
To get the output, we will print “myfile.read()” then the output will appear “ Python is one of
the good ”. So, it will truncate the file based on the given size which is ―25‖.

14.file flush() method:


The flush() method is an inbuilt method in python. It is used to clear the internal buffer when
writing to file. It is the best method while working with file handling in python.
#Example:
myfile = open("examplefile.txt", "a")
myfile.write("Welcome to python")
myfile.flush()
myfile.write("Programming.....")
To see the output, we will use “myfile.flush()” and it will clear the internal buffer of the file.
But, it does not affect the content of the file. So, the content of the file can be read and displayed.

15. file tell() method:


Python file tell() method returns the current file position within the file. It does not take any
parameter and returns an integer value.
#Example:
myfile = open("examplefile.txt", "r")
print(myfile.tell())
myfile.close()
Here, when we will print “myfile.tell()” then the output will appear “ 0 ”. Here, initially file
pointer points to the beginning of the file if not opened in append mode. So, the initial value of
tell() is zero.

16. Next()
file.next is helpful while iterating a file through a loop. Every time it‘s been called, it takes the
next line.
Example:
Our file ―Hello.txt‖ has 3 lines shown below,
Python File Methods eg4
Code:
ff = open("C:/Users/Test/desktop/Hello.txt", "r")
print(ff.next())
print(ff.next())
Output:

Page 103
PYTHON PROGRAMMING KG College of Arts and Science
Python File Methods

17.writelines() :
Like the way readlines used to read string line by line, in iteration form. Similar way writelines
is used to write string line if that‘s in an iterable object form.
#Code Example
f = open("sample_EDUCBA.txt","w+")
iter_seq = ["This is good platform\n", "Datascience is buzzword"] line = f.writelines( iter_seq )
f.close()

Output:
In the python console,Python File Methods eg5.1
The generated file is,
python generated file

18. File write() Method

The write() method writes a specified text to the file.Where the specified text will be inserted
depends on the file mode and stream position.

"a": The text will be inserted at the current file stream position, default at the end of the file.

"w": The file will be emptied before the text will be inserted at the current file stream position,
default 0.

Syntax:
file.write(byte)
Parameter Values
Parameter Description
byte The text or byte object that will be inserted.

#Example
Open the file with "a" for appending, then add some text to the file:
f = open("demofile2.txt", "a")
f.write("See you soon!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())
#More examples
# Example
#The same example as above, but inserting a line break before the inserted text:
f = open("demofile2.txt", "a")
f.write("\nSee you soon!")
f.close()

Page 104
PYTHON PROGRAMMING KG College of Arts and Science
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
19.File writelines() Method

The writelines() method writes the items of a list to the file.Where the texts will be inserted
depends on the file mode and stream position.

"a": The texts will be inserted at the current file stream position, default at the end of the file.

"w": The file will be emptied before the texts will be inserted at the current file stream position,
default 0.

#Syntax
file.writelines(list)
Parameter Values
Parameter Description
list The list of texts or byte objects that will be inserted.

#Example
#Open the file with "a" for appending, then add a list of texts to append to the file:
f = open("demofile3.txt", "a")
f.writelines(["See you soon!", "Over and out."])
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())
#More examples
#Example
The same example as above, but inserting line breaks for each list item:
f = open("demofile3.txt", "a")
f.writelines(["\nSee you soon!", "\nOver and out."])
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())

4. 10 FILE DIRECTORY :
If there are a large number of files to handle in our Python program, can arrange our code
within different directories to make things more manageable.A directory or folder is a collection
of files and subdirectories. Python has the os module that provides us with many useful methods
to work with directories (and files as well).
OS module in Python provides functions for interacting with the operating system. OS
comes under Python‘s standard utility modules. This module provides a portable way of using
operating system dependent functionality. All functions in os module raise OSError in the case
of invalid or inaccessible file names and paths, or other arguments that have the correct type
but are not accepted by the operating system.

In case new to programming, directories are nothing but folders. These directories are

Page 105
PYTHON PROGRAMMING KG College of Arts and Science
present inside a root folder eg: C:\ or D:\ and each directory could contain files or
subdirectories.

To retrieve a file in Python, you need to know the exact path to reach the file, in Windows, you
can view a particular file‘s path by right-clicking the File-> Properties-> General-> Location.

Similarly, to run a script, the working directory needs to be set to the directory containing the
script. However, while trying to run multiple scripts or while handling files the Current Working
Directory (CWD) is important.

Python would not be able to access the files if they aren't in the CWD. It is in these scenarios
that the Python ‗get current directory‘ command helps you know which directory you are in
currently.

i)Get Current Directory :


Get the present working directory using the getcwd() method of the os module.This method
returns the current working directory in the form of a string. Can also use the getcwdb() method
to get it as bytes object. To return the directory you are currently in, use the OS module to
interact with the operating system. Under the OS module, use the os.getcwd() method to
return the path of the current directory.

Syntax of os.getcwd:
os.getcwd()
#Code for python get current directory:
#importing the os module
import os
#to get the current working directory
directory = os.getcwd()
print(directory)

The output may vary depending on the directory you are in but it would start from the root
folder eg: D:\ and the directory prefixed by a \.

#Another Example:
>>> import os
>>> os.getcwd()
'C:\\Program Files\\PyScripter'
>>> os.getcwdb()
b'C:\\Program Files\\PyScripter'
The extra backslash implies an escape sequence. print() function will render this properly.
>>> print(os.getcwd())
C:\Program Files\PyScripter
>>> os.chdir('C:\\Python33')

ii)Changing Directory :
Change the current working directory by using the chdir() method. The new path that is to
change into must be supplied as a string to this method. Can use both the forward-slash / or the
backward-slash \ to separate the path elements. It is safer to use an escape sequence when using
the backward slash.

Page 106
PYTHON PROGRAMMING KG College of Arts and Science
>>> print(os.getcwd())
C:\Python33
Similar to the os.getcwd method used in Python to get the current directory, use the chdir()
methods in the os module to change the current directory.The current directory is changed to
retrieve files or run scripts that are present in other directories.
Syntax of chdir():
os.chdir(path)

Parameters:
path - The path to the new directory

#Code to change current directory:


To change the current directory to a subdirectory called "ct" that is present inside the "cas"
directory.

#Example
import os
os.chdir("C:\cas\ct")

iii)The rmdir() Method


The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should be removed.
Syntax
os.rmdir('dirname')
#Example
Following is the example to remove "/tmp/test" directory. It is required to give fully qualified
name of the directory, otherwise it would search for that directory in the current directory.
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )

iv)list the Directories and Files


All files and sub-directories inside a directory can be retrieved using the listdir() method. This
method takes in a path and returns a list of subdirectories and files in that path. If no path is
specified, it returns the list of subdirectories and files from the current working directory.
>>> print(os.getcwd())
C:\Python33

>>> os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']
Page 107
PYTHON PROGRAMMING KG College of Arts and Science

>>> os.listdir('G:\\')
['$RECYCLE.BIN',
'Movies',
'Music',
'Photos',
'Series',
'System Volume Information']

v)Making a New Directory :


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.
>>> os.mkdir('test')
>>> os.listdir()
['test']

vi)Renaming a Directory or a File :


The rename() method can rename a directory or a file. For renaming any directory or file,
the rename() method takes in two basic arguments: the old name as the first argument and the
new name as the second argument.
>>> os.listdir()
['test']
>>> os.rename('test','new_one')
>>> os.listdir()
['new_one']

vii)Removing Directory or File :

A file can be removed (deleted) using the remove() method. Similarly, the rmdir() method
removes an empty directory.

>>> os.listdir()

['new_one', 'old.txt']

>>> os.remove('old.txt')

>>> os.listdir()

['new_one']

>>> os.rmdir('new_one')

>>> os.listdir()

[]

Note: The rmdir() method can only remove empty directories.


In order to remove a non-empty directory, we can use the rmtree() method inside the shutil
module.
Page 108
PYTHON PROGRAMMING KG College of Arts and Science
>>> os.listdir()
['test']
>>> os.rmdir('test')
Traceback (most recent call last):
...
OSError: [WinError 145] The directory is not empty: 'test'
>>> import shutil
>>> shutil.rmtree('test')
>>> os.listdir()

viii)Copying Files in Python

shutil offers a couple of functions for copying files. The most commonly used functions are
shutil.copy() and shutil.copy2(). To copy a file from one location to another using shutil.copy(),
do the following:

import shutil

src = 'path/to/file.txt'

dst = 'path/to/dest_dir'

shutil.copy(src, dst)

shutil.copy() is comparable to the cp command in UNIX based systems. shutil.copy(src, dst) will
copy the file src to the location specified in dst. If dst is a file, the contents of that file are
replaced with the contents of src. If dst is a directory, then src will be copied into that directory.
shutil.copy() only copies the file‘s contents and the file‘s permissions. Other metadata like the
file‘s creation and modification times are not preserved.

To preserve all file metadata when copying, use shutil.copy2():

import shutil

src = 'path/to/file.txt'

dst = 'path/to/dest_dir'

shutil.copy2(src, dst)

Using .copy2() preserves details about the file such as last access time, permission bits, last
modification time, and flags.

ix)Copying Directories

Page 109
PYTHON PROGRAMMING KG College of Arts and Science
While shutil.copy() only copies a single file, shutil.copytree() will copy an entire directory and
everything contained in it. shutil.copytree(src, dest) takes two arguments: a source directory and
the destination directory where files and folders will be copied to.

Here‘s an example of how to copy the contents of one folder to a different location:

>>> import shutil

>>> shutil.copytree('data_1', 'data1_backup')

.'data1_backup'

In this example, .copytree() copies the contents of data_1 to a new location data1_backup and
returns the destination directory. The destination directory must not already exist. It will be
created as well as missing parent directories. shutil.copytree() is a good way to back up your
files.

x)Moving Files and Directories

To move a file or directory to another location, use shutil.move(src, dst).src is the file or
directory to be moved and dst is the destination:

>>> import shutil

>>> shutil.move('dir_1/', 'backup/')

'backup'

shutil.move('dir_1/', 'backup/') moves dir_1/ into backup/ if backup/ exists. If backup/ does not
exist, dir_1/ will be renamed to backup.

4. 11 USING PIPES AS DATA STREAMS :

os.pipe() method in Python is used to create a pipe. A pipe is a method to pass information
from one process to another process. It offers only one-way communication and the passed
information is held by the system until it is read by the receiving process.

Pipes, another cross-program communication device, are made available in Python with the
built-in os.pipe call. Pipes are unidirectional channels that work something like a shared memory
buffer, but with an interface resembling a simple file on each of two ends. In typical use, one
program writes data on one end of the pipe, and another reads that data on the other end. Each
program sees only its end of the pipes and processes it using normal Python file calls.

Pipes are much more within the operating system, though. For instance, calls to read a pipe will
normally block the caller until data becomes available (i.e., is sent by the program on the other
end) instead of returning an end-of-file indicator. Because of such properties, pipes are also a
way to synchronize the execution of independent programs.

Pipes come in two flavors anonymous and named. Named pipes (sometimes called fifos) are
represented by a file on your computer. Anonymous pipes exist only within processes, though,
and are typically used in conjunction with process forks as a way to link parent and spawned
Page 110
PYTHON PROGRAMMING KG College of Arts and Science
child processes within an application; parent and child converse over shared pipe file descriptors.
Because named pipes are really external files, the communicating processes need not be related
at all (in fact, they can be independently started programs).

1.Named Pipes (Fifos)


On some platforms, it is also possible to create a pipe that exists as a file. Such files are called
named pipes (or, sometimes, fifos) because they behave just like the pipes created within the
previous section's programs but are associated with a real file somewhere on your computer,
external to any particular program.

Once a named pipe file is created, processes read and write it using normal file operations. Fifos
are unidirectional streams. In typical operation, a server program reads data from the fifo, and
one or more client programs write data to it. But a set of two fifos can be used to implement
bidirectional communication just as we did for anonymous pipes in the prior section.

Because fifos reside in the filesystem, they are longer-lived than in-process anonymous pipes
and can be accessed by programs started independently. The unnamed, in-process pipe examples
thus far depend on the fact that file descriptors (including pipes) are copied to child processes'
memory. That makes it difficult to use anonymous pipes to connect programs started
independently. With fifos, pipes are accessed instead by a filename visible to all programs
running on the computer, regardless of any parent/child process relationships.

Because of that, fifos are better suited as general IPC mechanisms for independent client and
server programs. For instance, a perpetually running server program may create and listen for
requests on a fifo that can be accessed later by arbitrary clients not forked by the server. In a
sense, fifos are an alternative to the socket interface we'll meet in the next part of this book, but
fifos do not directly support remote network connections, are not available on as many platforms,
and are accessed using the standard file interface instead of the more unique socket port numbers
and calls we'll study later.

In Python, named pipe files are created with the os.mkfifo call, available today on Unix-like
platforms but not on all flavors of Windows (though this call is also available in Cygwin Python
on Windows). This creates only the external file, though; to send and receive data through a fifo,
it must be opened and processed as if it were a standard file.

Syntax: os.pipe()

Parameter: No parameter is required

Return Type: This method returns a pair of file descriptors (r, w) usable for reading and writing,
respectively.

#Code: Use of os.pipe() method


# Python program to explain os.pipe() method
# importing os module
import os

# Create a pipe
r, w = os.pipe()

Page 111
PYTHON PROGRAMMING KG College of Arts and Science
# The returned file descriptor r and w can be used for reading and writing respectively.
# We will create a child process and using these file descriptor the parent process will write
# some text and child process will read the text written by the parent process
# Create a child process
pid = os.fork()

# pid greater than 0 represents


# the parent process
if pid > 0:

# This is the parent process


# Closes file descriptor r
os.close(r)

# Write some text to file descriptor w


print("Parent process is writing")
text = b"Hello child process"
os.write(w, text)
print("Written text:", text.decode())

else:

# This is the parent process


# Closes file descriptor w
os.close(w)

# Read the text written by parent process


print("\nChild Process is reading")
r = os.fdopen(r)
print("Read text:", r.read())
Output:
Parent process is writing
Text written: Hello child process

Child Process is reading


Text read: Hello child process

Another Example:
Return Value
This method returns a pair of file descriptors.
Example
The following example shows the usage of pipe() method.
import os, sys

print "The child will write text to a pipe and "


print "the parent will read the text written by child..."

# file descriptors r, w for reading and writing


r, w = os.pipe()

Page 112
PYTHON PROGRAMMING KG College of Arts and Science
processid = os.fork()
if processid:
# This is the parent process
# Closes file descriptor w
os.close(w)
r = os.fdopen(r)
print "Parent reading"
str = r.read()
print "text =", str
sys.exit(0)
else:
# This is the child process
os.close(r)
w = os.fdopen(w, 'w')
print "Child writing"
w.write("Text written by child...")
w.close()
print "Child closing"
sys.exit(0)
When we run above program, it produces following result −
The child will write text to a pipe and
the parent will read the text written by child...
Parent reading
Child writing
Child closing
text = Text written by child...

2.Another pipe() method :


os.mkfifo() method in Python is used to create a FIFO (a named pipe) named path with the
specified mode. FIFOs are named pipe which can be accessed like other regular files. This
method only create FIFO but don‘t open it and the created FIFO does exist until they are deleted.
FIFOs are generally us as rendezvous between client and ―server type processes.

Syntax: os.mkfifo(path, mode = 0o666, *, dir_fd = None)

Parameters:
path: A path-like object representing the file system path. It can be a string or bytes object
representing a file path.
mode (optional): A numeric value representing the mode of the FIFO (named pipe) to be created.
The default value of mode parameter is 0o666 (octal).
dir_fd (optional): This is a file descriptor referring to a directory.

Note: The ‗*‘ in parameter list indicates that all following parameters (Here in our case ‗dir_fd‘)
are keyword-only parameters and they can be provided using their name, not as a positional
parameter.

Return type: This method does not return any value.

Page 113
PYTHON PROGRAMMING KG College of Arts and Science

Code: Use of os.mkfifo() method

# Python3 program to explain os.mkfifo() method

# importing os module
import os

# Path
path = "./mypipe"

# Mode of the FIFO (a named pipe)


# to be created
mode = 0o600

# Create a FIFO named path


# with the specified mode
# using os.mkfifo() method
os.mkfifo(path, mode)

print("FIFO named '% s' is created successfully." % path)


Output:
FIFO named './mypipe' is created successfully.

END OF UNIT-IV

UNIT – V
OBJECT ORIENTED FEATURES: Classes Principles of Object Orientation - Creating
Classes - Instance Methods - File Organization - Special Methods - Class Variables – Inheritance
– Polymorphism - Type Identification - Simple Character Matches - Special Characters -
Character Classes – Quantifiers - Dot Character - Greedy Matches – Grouping - Matching at
Beginning or End - Match Objects – Substituting - Splitting a String - Compiling Regular
Expressions. (10)

5. PYTHON OBJECT ORIENTED FEATURES :

In Python, Object-Oriented Programming (OOPs) is a programming paradigm that uses


objects and classes in programming. It aims to implement real-world entities like inheritance,
polymorphisms, encapsulation, etc. in the programming. The main concept of OOPs is to bind
the data and the functions that work on that together as a single unit so that no other part of the
code can access this data.
Object-Oriented Programming (OOP) is a method of structuring a program by
bundling related properties and behaviors into individual objects. Conceptually, objects are like
Page 114
PYTHON PROGRAMMING KG College of Arts and Science
the components of a system. Think of a program as a factory assembly line of sorts. At each step
of the assembly line a system component processes some material, ultimately transforming raw
material into a finished product. An object contains data, like the raw or preprocessed materials
at each step on an assembly line, and behavior, like the action each assembly line component
performs.
What is Object-Oriented Programming in Python?
Object-oriented programming is a programming paradigm that provides a means of
structuring programs so that properties and behaviors are bundled into individual objects. For
instance, an object could represent a person with properties like a name, age, and address
and behaviors such as walking, talking, breathing, and running. Or it could represent
an email with properties like a recipient list, subject, and body and behaviors like adding
attachments and sending. Put another way, object-oriented programming is an approach for
modeling concrete, real-world things, like cars, as well as relations between things, like
companies and employees, students and teachers, and so on. OOP models real-world entities as
software objects that have some data associated with them and can perform certain functions.
Another common programming paradigm is procedural programming, which structures a
program like a recipe in that it provides a set of steps, in the form of functions and code blocks,
that flow sequentially in order to complete a task. The key takeaway is that objects are at the
center of object-oriented programming in Python, not only representing the data, as in procedural
programming, but in the overall structure of the program as well.

5.1 Main Concepts of Object-Oriented Programming (OOPs) :


 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance

What is the need for a Class in Python ?


Primitive data structures—like numbers, strings, and lists—are designed to represent simple
pieces of information, such as the cost of an apple, the name of a poem, or your favorite colors,
respectively. What if you want to represent something more complex?
For example, let‘s say to track employees in an organization. Need to store some basic
information about each employee, such as their name, age, position, and the year they started
working.
Page 115
PYTHON PROGRAMMING KG College of Arts and Science
One way to do this is to represent each employee as a list:

kirk = ["James Kirk", 34, "Captain", 2265]


spock = ["Spock", 35, "Science Officer", 2254]
mccoy = ["Leonard McCoy", "Chief Medical Officer", 2266]

There are a number of issues with this approach.


First, it can make larger code files more difficult to manage. If you reference kirk[0] several
lines away from where the kirk list is declared, will you remember that the element with
index 0 is the employee‘s name?
Second, it can introduce errors if not every employee has the same number of elements in the list.
In the mccoy list above, the age is missing, so mccoy[1] will return "Chief Medical
Officer" instead of Dr. McCoy‘s age.
A great way to make this type of code more manageable and more maintainable is to use classes.

5.2 What is a Class ?


A class is a collection of objects. class, which is like a blueprint for creating an object. A
class contains the blueprints or the prototype from which the objects are being created. It is a
logical entity that contains some attributes and methods.
To understand the need for creating a class let‘s consider an example, let‘s say you wanted
to track the number of dogs that may have different attributes like breed, age. If a list is used,
the first element could be the dog‘s breed while the second element could represent its age.
Let‘s suppose there are 100 different dogs, then how would you know which element is
supposed to be which? What if you wanted to add other properties to these dogs? This lacks
organization and it‘s the exact need for classes.

Some points on Python class:


 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute

Class Definition Syntax:


class ClassName:
# Statement-1
.
.
# Statement-N
Example: Creating an empty Class in Python
•Python3 program to demonstrate defining a class
class Dog:
pass

In the above example, have created a class named dog using the class keyword.

How to Define a Class


All class definitions start with the class keyword, which is followed by the name of the class
and a colon. Any code that is indented below the class definition is considered part of the class‘s
body.
Here‘s an example of a Dog class:

Page 116
PYTHON PROGRAMMING KG College of Arts and Science
class Dog:
pass

The body of the Dog class consists of a single statement: the pass keyword. pass is often used as
a placeholder indicating where code will eventually go. It allows you to run this code without
Python throwing an error.

OBJECTS :

The object is an entity that has a state and behavior associated with it. It may be any real -world
object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers,
even arrays, and dictionaries, are all objects. More specifically, any single integer or any single
string is an object. The number 12 is an object, the string ―Hello, world‖ is an object, a list is
an object that can hold other objects, and so on.
An object consists of : (SBI)
 State: It is represented by the attributes of an object. It also reflects the properties of an
object.
 Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other
objects.
To understand the State, Behavior, and Identity let us take the example of the class dog
(explained above).
 The identity can be considered as the name of the dog.
 State or Attributes can be considered as the breed, age, or color of the dog.
 The behavior can be considered as to whether the dog is eating or sleeping.

#Example: Creating an object

obj = Dog()

This will create an object named obj of the class Dog defined above. Before diving deep into
objects and class let us understand some basic keywords that used while working with objects
and classes.
The self
1. Class methods must have an extra first parameter in the method definition. Value for this
parameter when the method is called , Python provides it.
2. If we have a method that takes no arguments, then we still have to have one argument.
3. This is similar to this pointer in C++ and this reference in Java.
When call a method of this object as myobject.method(arg1, arg2), this is automatically
converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is
about.
The __init__ method
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object
of a class is instantiated. The method is useful to do any initialization you want to do with your
object.
Now let us define a class and create some objects using the self and __init__ method.
Example 1: Creating a class and object with class and instance attributes
•Python3
class Dog:
# class attribute
attr1 = "mammal"
Page 117
PYTHON PROGRAMMING KG College of Arts and Science
# Instance attribute
def __init__(self, name):
self.name = name
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Accessing class attributes
print("Rodger is a {}".format(Rodger.__class__.attr1))
print("Tommy is also a {}".format(Tommy.__class__.attr1))
# Accessing instance attributes
print("My name is {}".format(Rodger.name))
print("My name is {}".format(Tommy.name))

Output
Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy
#Example 2: Creating Class and objects with methods
class Dog:

# class attribute
attr1 = "mammal"

# Instance attribute
def __init__(self, name):
self.name = name

def speak(self):
print("My name is {}".format(self.name))

# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Accessing class methods
Rodger.speak()
Tommy.speak()

Output
My name is Rodger
My name is Tommy

Classes vs Instances :
Classes are used to create user-defined data structures. Classes define functions called methods,
which identify the behaviors and actions that an object created from the class can perform with
its data. Create a Dog class that stores some information about the characteristics and behaviors
that an individual dog can have.

Page 118
PYTHON PROGRAMMING KG College of Arts and Science
A class is a blueprint for how something should be defined. It doesn‘t actually contain any
data. The Dog class specifies that a name and an age are necessary for defining a dog, but it
doesn‘t contain the name or age of any specific dog.
While the class is the blueprint, an instance is an object that is built from a class and contains
real data. An instance of the Dog class is not a blueprint anymore. It‘s an actual dog with a name,
like Miles, who‘s four years old.
Put another way, a class is like a form or questionnaire. An instance is like a form that has been
filled out with information. Just like many people can fill out the same form with their own
unique information, many instances can be created from a single class.
Instantiate an Object in Python
Open IDLE‘s interactive window and type the following:

>>> class Dog:


... pass

This creates a new Dog class with no attributes or methods. Creating a new object from a class is
called instantiating an object. can instantiate a new Dog object by typing the name of the class,
followed by opening and closing parentheses:

>>> Dog()
<__main__.Dog object at 0x106702d30>

now have a new Dog object at 0x106702d30. This funny-looking string of letters and numbers is
a memory address that indicates where the Dog object is stored in your computer‘s memory.
Note that the address you see on your screen will be different.
Now instantiate a second Dog object:

>>> Dog()
<__main__.Dog object at 0x0004ccc90>

The new Dog instance is located at a different memory address. That‘s because it‘s an entirely
new instance and is completely unique from the first Dog object that you instantiated.
To see this another way, type the following:

>>> a = Dog()
>>> b = Dog()
>>> a == b
False

In this code, create two new Dog objects and assign them to the variables a and b. When you
compare a and b using the == operator, the result is False. Even though a and b are both
instances of the Dog class, they represent two distinct objects in memory.

The Dog class isn‘t very interesting right now, so let‘s spruce it up a bit by defining some
properties that all Dog objects should have. There are a number of properties that we can choose

Page 119
PYTHON PROGRAMMING KG College of Arts and Science
from, including name, age, coat color, and breed. To keep things simple, we‘ll just use name and
age.
The properties that all Dog objects must have are defined in a method called .__init__().
Every time a new Dog object is created, .__init__() sets the initial state of the object by
assigning the values of the object‘s properties. That is, .__init__() initializes each new
instance of the class.
Can give .__init__() any number of parameters, but the first parameter will always be
a variable called self. When a new class instance is created, the instance is automatically passed
to the self parameter in .__init__() so that new attributes can be defined on the object.
Let‘s update the Dog class with an .__init__() method that creates .name and .age attributes:

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

Notice that the .__init__() method‘s signature is indented four spaces. The body of the
method is indented by eight spaces. This indentation is vitally important. It tells Python that
the .__init__() method belongs to the Dog class.
In the body of .__init__(), there are two statements using the self variable:
1. self.name = name creates an attribute called name and assigns to it the value of
the name parameter.
2. self.age = age creates an attribute called age and assigns to it the value of
the age parameter.
Attributes created in .__init__() are called instance attributes. An instance attribute‘s value
is specific to a particular instance of the class. All Dog objects have a name and an age, but the
values for the name and age attributes will vary depending on the Dog instance.
On the other hand, class attributes are attributes that have the same value for all class instances.
You can define a class attribute by assigning a value to a variable name outside of .__init__().
For example, the following Dog class has a class attribute called species with the value "Canis
familiaris":

class Dog:
# Class attribute
species = "Canis familiaris"

def __init__(self, name, age):


self.name = name
self.age = age

Class attributes are defined directly beneath the first line of the class name and are indented by
four spaces. They must always be assigned an initial value. When an instance of the class is
created, class attributes are automatically created and assigned to their initial values.
Use class attributes to define properties that should have the same value for every class instance.
Use instance attributes for properties that vary from one instance to another.
Now in Dog class, let‘s create some dogs!

Class and Instance Attributes:


Now create a new Dog class with a class attribute called .species and two instance attributes
called .name and .age:
Page 120
PYTHON PROGRAMMING KG College of Arts and Science
>>> class Dog:
... species = "Canis familiaris"
... def __init__(self, name, age):
... self.name = name
... self.age = age

To instantiate objects of this Dog class, need to provide values for the name and age. If you don‘t,
then Python raises a TypeError:
>>> Dog()
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
Dog()
TypeError: __init__() missing 2 required positional arguments: 'name' and 'age'

To pass arguments to the name and age parameters, put values into the parentheses after the class
name:
>>> buddy = Dog("Buddy", 9)
>>> miles = Dog("Miles", 4)

This creates two new Dog instances—one for a nine-year-old dog named Buddy and one for a
four-year-old dog named Miles.
The Dog class‘s .__init__() method has three parameters, so why are only two arguments
passed to it in the example?
When instantiate a Dog object, Python creates a new instance and passes it to the first parameter
of .__init__(). This essentially removes the self-parameter, so need to worry about
the name and age parameters.
After create the Dog instances, can access their instance attributes using dot notation:
>>> buddy.name
'Buddy'
>>> buddy.age
9

>>> miles.name
'Miles'
>>> miles.age
4
can access class attributes the same way:
>>> buddy.species
'Canis familiaris'

One of the biggest advantages of using classes to organize data is that instances are guaranteed
to have the attributes you expect. All Dog instances have .species, .name, and .age attributes,
so can use those attributes with confidence knowing that they will always return a value.
Although the attributes are guaranteed to exist, their values can be changed dynamically:
>>> buddy.age = 10
>>> buddy.age
10

>>> miles.species = "Felis silvestris"


>>> miles.species
'Felis silvestris'

Page 121
PYTHON PROGRAMMING KG College of Arts and Science
In this example, change the .age attribute of the buddy object to 10. Then change
the .species attribute of the miles object to "Felis silvestris", which is a species of cat.
That makes Miles a pretty strange dog, but it is valid Python!
The key takeaway here is that custom objects are mutable by default. An object is mutable if it
can be altered dynamically. For example, lists and dictionaries are mutable, but strings and
tuples are immutable.

5.3 CLASS VARIABLES and INSTANCE VARIABLES:


Object-oriented programming allows for variables to be used at the class level or the instance
level. Variables are essentially symbols that stand in for a value you‘re using in a program.
At the class level, variables are referred to as class variables, whereas variables at the instance
level are called instance variables.
When it is expected that variables are going to be consistent across instances, or like to
initialize a variable, can define that variable at the class level. When anticipate the variables will
change significantly across instances, can define them at the instance level.

A class variable alone looks like the following:


class Shark:
animal_type = "fish"

Here, the variable animal_type is assigned the value "fish".


can create an instance of the Shark class (call it new_shark) and print the variable by using dot
notation

class Shark:
animal_type = "fish"

new_shark = Shark()
print(new_shark.animal_type)

Output
fish
program returns the value of the variable.
Add a few more class variables and print them out
#shark.py
class Shark:
animal_type = "fish"
location = "ocean"
followers = 5

new_shark = Shark()
print(new_shark.animal_type)
print(new_shark.location)
print(new_shark.followers)

Page 122
PYTHON PROGRAMMING KG College of Arts and Science
Just like with any other variable, class variables can consist of any data type available to us in
Python. In this program have strings and an integer. Let‘s run the program again with the python
shark.py command and review the output:
Output
fish
ocean
5

The instance of new_shark is able to access all the class variables and print them out when run
the program.
Class variables allow us to define variables upon constructing the class. These variables and their
associated values are then accessible to each instance of the class.
5.3.1 INSTANCE VARIABLES
Instance variables are owned by instances of the class. This means that for each object or
instance of a class, the instance variables are different. Unlike class variables, instance variables
are defined within methods.
In the Shark class example below, name and age are instance variables:
class Shark:
def __init__(self, name, age):
self.name = name
self.age = age

When create a Shark object, we will have to define these variables, which are passed as
parameters within the constructor method or another method.
class Shark:
def __init__(self, name, age):
self.name = name
self.age = age

new_shark = Shark("Sammy", 5)

As with class variables, can similarly call to print instance variables:


#shark.py
class Shark:
def __init__(self, name, age):
self.name = name
self.age = age

new_shark = Shark("Sammy", 5)
print(new_shark.name)
print(new_shark.age)

When run the program above with python shark.py, receive the following output:
Output
Sammy
5

The output received is made up of the values of the variables that we initialized for the object
instance of new_shark.
Let‘s create another object of the Shark class called stevie:
#shark.py
class Shark:
def __init__(self, name, age):
Page 123
PYTHON PROGRAMMING KG College of Arts and Science
self.name = name
self.age = age

new_shark = Shark("Sammy", 5)
print(new_shark.name)
print(new_shark.age)

stevie = Shark("Stevie", 8)
print(stevie.name)
print(stevie.age)

Output
Sammy
5
Stevie
8

The stevie object, like the new_shark object passes the parameters specific for that instance of the Shark
class to assign values to the instance variables.
Instance variables, owned by objects of the class, allow for each object or instance to have different
values assigned to those variables.

5.3.2 Working with Class and Instance Variables together :


Class variables and instance variables will often be utilized at the same time, so let‘s look at an
example of this using the Shark class we created. The comments in the program outline each
step of the process.
#shark.py
class Shark:

# Class variables
animal_type = "fish"
location = "ocean"

# Constructor method with instance variables name and age


def __init__(self, name, age):
self.name = name
self.age = age

# Method with instance variable followers


def set_followers(self, followers):
print("This user has " + str(followers) + " followers")

def main():
# First object, set up instance variables of constructor method
sammy = Shark("Sammy", 5)

# Print out instance variable name


print(sammy.name)

# Print out class variable location


Page 124
PYTHON PROGRAMMING KG College of Arts and Science
print(sammy.location)

# Second object
stevie = Shark("Stevie", 8)

# Print out instance variable name


print(stevie.name)

# Use set_followers method and pass followers instance variable


stevie.set_followers(77)

# Print out class variable animal_type


print(stevie.animal_type)

if __name__ == "__main__":
main()

When run the program with python shark.py, receive the following output:
Output
Sammy
ocean
Stevie
This user has 77 followers
fish
Here, it is made use of both class and instance variables in two objects of
the Shark class, sammy and stevie.

5.4 INSTANCE METHODS :


Instance methods are functions that are defined inside a class and can only be called from an
instance of that class. Just like .__init__(), an instance method‘s first parameter is
always self.
Open a new editor window in IDLE and type in the following Dog class:
class Dog:
species = "Canis familiaris"

def __init__(self, name, age):


self.name = name
self.age = age

# Instance method
def description(self):
return f"{self.name} is {self.age} years old"

# Another instance method


def speak(self, sound):
return f"{self.name} says {sound}"

This Dog class has two instance methods:


1. .description() returns a string displaying the name and age of the dog.
2. .speak() has one parameter called sound and returns a string containing the dog‘s
name and the sound the dog makes.

Page 125
PYTHON PROGRAMMING KG College of Arts and Science
Save the modified Dog class to a file called dog.py and press F5 to run the program. Then open
the interactive window and type the following to see your instance methods in action:
>>>
>>> miles = Dog("Miles", 4)

>>> miles.description()
'Miles is 4 years old'

>>> miles.speak("Woof Woof")


'Miles says Woof Woof'

>>> miles.speak("Bow Wow")


'Miles says Bow Wow'

In the above Dog class, .description() returns a string containing information about
the Dog instance miles. When writing user‘s own classes, it‘s a good idea to have a method that
returns a string containing useful information about an instance of the class.
However, .description() isn‘t the most Pythonic way of doing this.
When a list object is created , can use print() to display a string that looks like the list:
>>>
>>> names = ["Fletcher", "David", "Dan"]
>>> print(names)
['Fletcher', 'David', 'Dan']
Let‘s see what happens when you print() the miles object:
>>>
>>> print(miles)
<__main__.Dog object at 0x00aeff70>

On use of print(miles),get a cryptic looking message telling that miles is a Dog object at the
memory address 0x00aeff70. This message isn‘t very helpful. Can change what gets printed by
defining a special instance method called .__str__().
In the editor window, change the name of the Dog class‘s .description() method
to .__str__():
class Dog:
# Leave other parts of Dog class as-is
# Replace .description() with __str__()
def __str__(self):
return f"{self.name} is {self.age} years old"
Save the file and press F5 . Now, when you print(miles), you get a much friendlier output:

>>> miles = Dog("Miles", 4)


>>> print(miles)
'Miles is 4 years old'
Methods like .__init__() and .__str__() are called dunder methods because they begin and
end with double underscores. There are many dunder methods that you can use to customize
classes in Python. Although too advanced a topic for a beginning Python book, understanding
dunder methods is an important part of mastering object-oriented programming in Python.

5.5 CREATE CLASSES FROM OTHER CLASSES :


5.5.1 Inherit From Other Classes in Python

Page 126
PYTHON PROGRAMMING KG College of Arts and Science
Inheritance is the process by which one class takes on the attributes and methods of another.
Newly formed classes are called child classes, and the classes that child classes are derived from
are called parent classes.
Child classes can override or extend the attributes and methods of parent classes. In other words,
child classes inherit all of the parent‘s attributes and methods but can also specify attributes and
methods that are unique to themselves.
Parent Classes vs Child Classes :
Let‘s create a child class for each of the three breeds mentioned above: Jack Russell Terrier,
Dachshund, and Bulldog. For reference, here‘s the full definition of the Dog class:

class Dog:
species = "Canis familiaris"

def __init__(self, name, age):


self.name = name
self.age = age

def __str__(self):
return f"{self.name} is {self.age} years old"

def speak(self, sound):


return f"{self.name} says {sound}"

Remember, to create a child class, you create new class with its own name and then put the name
of the parent class in parentheses. Add the following to the dog.py file to create three new child
classes of the Dog class:
class JackRussellTerrier(Dog):
pass

class Dachshund(Dog):
pass

class Bulldog(Dog):
pass

Press F5 to save and run the file. With the child classes defined, can now instantiate some dogs
of specific breeds in the interactive window:
>>>
>>> miles = JackRussellTerrier("Miles", 4)
>>> buddy = Dachshund("Buddy", 9)
>>> jack = Bulldog("Jack", 3)
>>> jim = Bulldog("Jim", 5)
Instances of child classes inherit all of the attributes and methods of the parent class:
>>>
>>> miles.species
'Canis familiaris'

>>> buddy.name
'Buddy'

Page 127
PYTHON PROGRAMMING KG College of Arts and Science
>>> print(jack)
Jack is 3 years old

>>> jim.speak("Woof")
'Jim says Woof'
To determine which class a given object belongs to, you can use the built-in type():
>>>
>>> type(miles)
<class '__main__.JackRussellTerrier'>
What if you want to determine if miles is also an instance of the Dog class? You can do this with
the built-in isinstance():
>>>
>>> isinstance(miles, Dog)
True

Notice that isinstance() takes two arguments, an object and a class. In the example
above, isinstance() checks if miles is an instance of the Dog class and returns True.
The miles, buddy, jack, and jim objects are all Dog instances, but miles is not
a Bulldog instance, and jack is not a Dachshund instance:
>>>
>>> isinstance(miles, Bulldog)
False

>>> isinstance(jack, Dachshund)


False

More generally, all objects created from a child class are instances of the parent class, although
they may not be instances of other child classes.
Now that created child classes for some different breeds of dogs, let‘s give each breed its own
sound.
5.6 INHERITANCE :
Inheritance is the capability of one class to derive or inherit the properties from another class.
The class that derives properties is called the derived class or base class and the class from
which the properties are being derived is called the base class or parent class. The benefits of
inheritance are:
 It represents real-world relationships well.
 It provides the reusability of a code. We don‘t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
 It is transitive in nature, which means that if class B inherits from another class A, then all
the subclasses of B would automatically inherit from class A.
Example: Inheritance in Python
# Python code to demonstrate how parent constructors are called parent class
class Person(object):
# __init__ is known as the constructor
def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("My name is {}".format(self.name))

Page 128
PYTHON PROGRAMMING KG College of Arts and Science
print("IdNumber: {}".format(self.idnumber))
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
# invoking the __init__ of the parent class
Person.__init__(self, name, idnumber)

def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))

# creation of an object variable or an instance


a = Employee('Rahul', 886012, 200000, "Intern")
# calling a function of the class Person using its instance
a.display()
a.details()
Output
Rahul
886012
My name is Rahul
IdNumber: 886012
Post: Intern

5.6.1 WHAT IS AN INHERITANCE IN PYTHON?

Just like a parent-child relationship, inheritance works on derived classes relative to the base
class. Every ―Derived‖ class inherits from a ―Base‖ class. The inheritance is represented in UML
or Unified Modeling Language. It is a standard modeling language that includes an integrated set
of diagrams to help developers specify, structure, and document software systems elements.
Inheritance relationship defines the classes that inherit from other classes as derived, subclass, or
sub-type classes. Base class remains to be the source from which a subclass inherits. For
example, you have a Base class of ―Animal,‖ and a ―Lion‖ is a Derived class. The inheritance
will be Lion is an Animal.
So, the question is, what does the “Lion” class inherit from “Animal”?
A ―Lion‖ class inherits

Page 129
PYTHON PROGRAMMING KG College of Arts and Science
 Interface
 Execution
Advantages of Inheritance in Python
 Inheritance in Python helps developers to reuse the objects.
 Each time a class inherits the base class, it gets access to the parent object‘s
functionality.
 Reusability due to inheritance is also reliable as the base class is already
tested.
 Low development time and cost
 Standardization of the interface across classes becomes easy.
 Reduces redundancy of code and help improve extensibility
 The creation of class libraries becomes easy.

5.6.2 TYPES OF INHERITANCE IN PYTHON :

1. SINGLE INHERITANCE
Single inheritance is- the inheritance of the ―Derived‖ class from the ―Base‖ class. Let‘s
understand it through an example,
class Country:
def ShowCountry(self):
print(―This is Spain‖);
class State(Country):
def ShowState(self):
print(―This is State‖);
st =State();
st.ShowCountry();
st.ShowState();

2.MULTI-LEVEL INHERITANCE

Page 130
PYTHON PROGRAMMING KG College of Arts and Science

Python is made of several objects, and with the multi-level inheritance, there are endless
possibilities of reusing the class functionalities. Multi-level inheritance gets documented each
time a derived class inherits another derived class. There is no limit to the number of derived
classes that can inherit the functionalities, and that is why multilevel inheritance helps to
improve the reusability in Python.

# Example of multilevel inheritance


class Animal:
def speak(self):
print(―Animal Speaking‖)
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print(―dog barking‖)
#The child class Dogchild inherits another child class
Dog
class DogChild(Dog):
def eat(self):
print(―Eating bread…‖)
d = DogChild()
d.bark()
d.speak()
d.eat()

Page 131
PYTHON PROGRAMMING KG College of Arts and Science
3. MULTIPLE INHERITANCE:

Python enables developers to inherit multiple functionalities and properties from different base
classes into a single derived class. It is mostly a great feature as it can allow you to inherit
multiple dependencies without extensive tools or coding.

#Example for multiple inheritances.


class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))

4.HIERARCHICAL INHERITANCE
Hierarchical inheritance involves multiple inheritance from the same base or parent class.
Page 132
PYTHON PROGRAMMING KG College of Arts and Science

#Example for hierarchical Inheritance


class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Parent):
def func3(self):
print("this is function 3")

ob = Child()
ob1 = Child2()
ob.func1()
ob.func2()

5.HYBRID INHERITANCE
Hybrid inheritance involves multiple inheritance taking place in a single program.
class Parent:
def func1(self):
print("this is function one")

class Child(Parent):
def func2(self):
print("this is function 2")

class Child1(Parent):
def func3(self):
print(" this is function 3"):

class Child3(Parent , Child1):


def func4(self):
print(" this is function 4")

ob = Child3()
ob.func1()

Page 133
PYTHON PROGRAMMING KG College of Arts and Science

How to identify a Derived Class?


Python comes with a built-in issubclass() function that helps developers check whether a class is
a derived one or a base class. Once you run this function, it returns with a result ―True‖ for
subclass or a Derived class, while False for Base class.

A developer can check the class through this example.


class myAge:
age = 36
class myObj(myAge):
name = ―John‖
age = myAge
x = issubclass(myObj, myAge)

How to create a class hierarchy in Python?


Inheritance in Python helps create hierarchies of classes. All the relative classes will share a
common interface to communicate with each other. A Base class defines the interface. Derived
classes can provide specific specialization of the interface. Here, exploring an HR model to
demonstrate the class hierarchy.
The HR system will process payroll for different company workers; each worker is identified
through an ID and has different payroll positions to be calculated.
Let‘s first create a payroll class as the ―Base‖ object.
# In hr.py
class PayrollSystem:
def calculate_payroll(self, workers):
print(‗Calculating Payroll‘)
print(‗===================‘)
for worker in workers:
print(f‘Payroll for: {worker.id} – {worker.name}‘)
print(f‘- Check amount: {worker.calculate_payroll()}‘)
print(‖)

The PayrollSystem executes a .calculate_payroll()method that collects the worker‘s information,


prints their id, name, and checks the payroll amount. Now, you run a base class worker that
tackles the standard interface for every worker type:
# In hr.py
class Worker:
def __init__(self, id, name):
self.id = id
self.name = name

Creating a Worker base class for all the worker types in the company makes the hierarchy easy
for the HR system. Every worker is assigned a name and id. The HR system requires the worker
to provide data regarding their weekly salary through the .calculate_payroll() interface. The
execution of this interface may differ according to the type of worker.

Why is inheritance significant in Python?


Inheritance refers to the process of passing on the properties of a parent class to a child class. It
is an object-oriented programming(OOP) concept and is significant in Python. It is because
inheritance provides code reusability, which means that instead of writing the same code over
Page 134
PYTHON PROGRAMMING KG College of Arts and Science
and again, we can inherit the attributes we require in a child class. It is also easy to understand
and implement since it depicts a real-world relationship between the parent and child classes. It
has a transitive nature. Because all child classes inherit properties from their parents, any
subclasses will likewise use the parent class's functionalities.

Is inheritance necessary while learning Python?


Yes, learning inheritance is necessary while learning Python. Massive python applications
necessitate a rise in the number of python programmers in the current market. This surge has led
to an increase in the number of people learning Python. The Python programming language is
rich in notions such as inheritance. One of the essential concepts in this Object-oriented
programming language is inheritance. As inheritance allows for code reusability, readability, and
properties transition, learning it while learning Python is imperative. Inheritance aids in creating
accurate and efficient code.

In Python, which types of inheritance are not supported?


Python allows all forms of inheritance, including multiple inheritances, unlike other object-
oriented programming languages. It is possible to construct new classes from pre-existing ones
using the inheritance concept. This facilitates the reuse of code. The methods specified in the
parent class are also used in the child class. While C++ also enables this sort of inheritance, it
lacks Python's advanced and well-designed methodology. Python even offers Hybrid inheritance,
which allows us to implement many types of inheritance in a single piece of code. Because code
reusability is a strength of inheritance, it is helpful in a wide range of applications when working
with Python.

The benefits of inheritance are:

1. It represents real-world relationships well.


2. It provides reusability of a code. We don‘t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
3. It is transitive in nature, which means that if class B inherits from another class A, then all
the subclasses of B would automatically inherit from class A.

5.7 POLYMORPHISM IN PYTHON:


Suppose there is a class called animal, but in that class, a whole lot of forms are there like
dog, cat, cow etc. That means a common class animal consists of different forms that exist in
various forms and shapes and have different functionalities. This whole thing can be defined
by a single term called polymorphism. Polymorphism in python is something that is used to
describe the ability to take various forms. The word is derived from two different words
poly which means many and morphs meaning forms. The literal meaning of polymorphism is
the condition of occurrence in different forms. Polymorphism is a very important concept in
programming. It refers to the use of a single type entity (method, operator or object) to represent
different types in different scenarios.

i)Constructor :
Constructor is a type of subroutine in object-oriented programming. Constructor is used to
assigning value to data members when an object is created inside a class. The __init__()
function is used as a constructor in python almost every time create an object. In
polymorphism, this __init__() function is used almost everywhere.

Page 135
PYTHON PROGRAMMING KG College of Arts and Science
What is polymorphism in Python?
Polymorphism in Python is used for a common function name that can be used for different
types. This concept is widely applied in object-oriented based Python programming. Like
other programming languages say Java, C+, polymorphism is also implemented in python for
different purpose commonly Duck Typing, Operator overloading and Method overloading,
and Method overriding. This polymorphism process can be achieved in two main ways
namely overloading and overriding.

#A simple example of polymorphism in python


#Example 1
>>>4+5
9

#Example 2
>>>‖4‖+‖5‖
45

#Example 3
>>>‖ab‖+‖cd‖
abcd

In the above example can clearly see that the addition operator is used in different way.
In the first example the as the data sent are two integer values, the operator did the addition
operation of two numbers.
And in the second example, as the same values are sent as data in the form of string, and the
same operator did the concatenation (concatenation is the process by which two strings ar e
joined end-to-end) of the two strings.
In the third example, the data sent are two strings but the operator is same as the above and
it did the concatenation of the two strings.

>>>‖3‖+‖ab‖
3ab

In this example the addition operator did the concatenation of the two strings though the first
value is a integer but here in this specific example it is sent as strings.
So these were the few basic examples of polymorphism in python.

5.7.1 How to use polymorphism?


A)Overloading
Overloading is divided into two types
i)Operator Overloading
ii)Method Overloading
i)Operator overloading
Operator overloading is the type of overloading in which an operator can be used in multiple
ways beyond its predefined meaning.

>>>print(2*7)
14

>>>print(‖a‖*3)
aaa

Page 136
PYTHON PROGRAMMING KG College of Arts and Science
So in the above example the multiplication operator did the multiplication of two numbers in
the first one, but in the second one as the multiplication of a string and an integer is not
possible so the character is printed repeatedly for 3 times. So it shows how a single operator
can be used in different way.

Application of operator overloading is done by overloading the special function


__add__ operator.

class Vehicle:
def __init__(self, fare):
self.fare = fare
def __add__(self, other)://using the special function __add__ operator
return self.fare+ other.fare

bus= Vehicle(20)
car= Vehicle(30)
total_fare=bus+ car
print(total_fare)

#Output:
50

Overloading the special function magically defines everytime plus operator is used in the
object total_fare=bus+ car . User is going to add their fares
#Example 2: Let us compare the fares of different vehicles in this example
class Vehicle:
def __init__(self, fare):
self.fare = fare
def __lt__(self, other):// relational operator __lt__ is used here as the special function
return self.fare< other.fare

bus= Vehicle(10)
car= Vehicle(30)
compare=bus< car
print(compare)

Output:
True

__lt__ It is the relational operator which is used as a special function for operator
overloading in the above example.

ii)Method Overloading
Method overloading means a class containing multiple methods with the same name but
may have different arguments. Basically python does not support method overloading, but
there are several ways to achieve method overloading. Though method overloading can be
achieved, the last defined methods can only be usable.
Let’s take an example for better understanding
Let‘s consider a class A, within the class have taken a function show which has a construct or
self and arguments whose default values assigned are None and None. User created an object
and called the function with the object obj.show, but didn‘t pass any argument though it will
print None and None cause in the function part assigned the default values.
Example:
Page 137
PYTHON PROGRAMMING KG College of Arts and Science
class A:
def show(self, a=None, b=None):
print(a,b)

obj=A()
obj.show()
Output
None None
Now to pass any other value then that need to call another function obj.show() with an
argument in it.
Example:
class A:
def show(self, a=None, b=None):
print(a,b)

obj=A()
obj.show()
obj.show(4)
Output
None None
4 None
Here in the output the None value assigned for a in the function part is replaced with 4. In
the function call part 4 is passed as the argument.
Now two argument is passed during the function call see what will happen in the next
example,
#Example:
class A:
def show(self, a=None, b=None):
print(a,b)

obj=A()
obj.show()
obj.show(4)
obj.show(4,5)
Output
None None
4
45

Here as two arguments 4 and 5 are passed during function call two different values are
assigned for a and b.So in the above example the same method and use different f unction
calls in different ways is seen

B)METHOD OVERRIDING :
Method overriding is the process of modifying a base class from the derived class having the
same methods and same number of arguments. Let‘s take an example and see how it
works. First of all create a base class with a method and then create a derived class without
any method,
#Example:
class Vehicle:
def run(self):
print("Saves Energy")
class EV(Vehicle):
pass

ev = EV()
Page 138
PYTHON PROGRAMMING KG College of Arts and Science
ev.run()

So when the function is called, the output will print the base class‘s method, as the derived
class has no method in it.

Output:
Saves Energy

Now in the next example declare another method under the derived class with the same
name as base class but with a different argument. As the base class‘s method is now
overridden by the derived class, only the derived class‘s method will be printed as the output.
#Example:
class Vehicle:
def run(self):
print("Saves Energy")

class EV(Vehicle):
def run(self):
print("Run on Electricity")

ev = EV()
ev.run()

Output
Run on Electricity

Duck Typing
Duck typing is a concept in polymorphism. The term duck typing is derived from the quote
which says something that walks like a duck quacks like a duck and swims like a duck is
called a duck no matter what object it is. In simple words it means something that matches
its behaviour to anything then it will consider a thing of that category to which it matches.

Why is polymorphism needed?

When Talking about object-oriented programming in python the term polymorphism will
come for sure. In object-oriented programming, objects need to take different forms. In
software development, it‘s quite important to have this feature. Through polymorphism, a
single action can be performed in various ways. This concept is widely used when we talk
about loose coupling, dependency injection and interface etc.

OTHER EXAMPLES OF POLYMORPHISM :


Example 1: Polymorphism in addition operator
Know that the + operator is used extensively in Python programs. But, it does not have a single
usage.
For integer data types, + operator is used to perform arithmetic addition operation.
#example
num1 = 1
num2 = 2
print(num1+num2)
Hence, the above program outputs 3.

Page 139
PYTHON PROGRAMMING KG College of Arts and Science
Similarly, for string data types, + operator is used to perform concatenation.

str1 = "Python"
str2 = "Programming"
print(str1+" "+str2)
As a result, the above program outputs Python Programming.
Here, a single operator + has been used to carry out different operations for distinct data types.
This is one of the most simple occurrences of polymorphism in Python.

Function Polymorphism in Python


There are some functions in Python which are compatible to run with multiple data types.
One such function is the len() function. It can run with many data types in Python. Let's look at
some example use cases of the function.
Example 2: Polymorphic len() function
print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))

Output
9
3
2
Here, many data types such as string, list, tuple, set, and dictionary can work with
the len() function. However, can see that it returns specific information about specific data
types.

Polymorphism in len() function in Python

Class Polymorphism in Python


Polymorphism is a very important concept in Object-Oriented Programming. Use the concept of
polymorphism while creating class methods as Python allows different classes to have methods
with the same name. Can then later generalize calling these methods by disregarding the object
working with. Let's look at an example:
Example 3: Polymorphism in Class Methods

Page 140
PYTHON PROGRAMMING KG College of Arts and Science
Here, we have created two classes Cat and Dog . They share a similar structure and have the
same method names info() and make_sound() .
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age

def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
print("Meow")

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def info(self):
print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
print("Bark")

cat1 = Cat("Kitty", 2.5)


dog1 = Dog("Fluffy", 4)

for animal in (cat1, dog1):


animal.make_sound()
animal.info()
animal.make_sound()
Output
Meow
I am a cat. My name is Kitty. I am 2.5 years old.
Meow
Bark
I am a dog. My name is Fluffy. I am 4 years old.
Bark

However, notice that it have not created a common superclass or linked the classes together in
any way. Even then, can pack these two different objects into a tuple and iterate through it using
a common animal variable. It is possible due to polymorphism.

5.8 SUPER() FUNCTION :


Now as if the base class‘s method has been overridden, the method from the base class
cannot be called normally. So to call the method of base class have to use the super function
in the overridden method under the derived class.
Example:
class Vehicle:
def run(self):
print("Saves Energy")

Page 141
PYTHON PROGRAMMING KG College of Arts and Science
class EV(Vehicle):
def run(self):
super().run()//super function is used to call the method of base class

print("Run on Electricity")

ev = EV()
ev.run()

Output:
Saves Energy
Run on Electricity

5.9 POLYMORPHISM AND INHERITANCE :


Like in other programming languages, the child classes in Python also inherit methods and
attributes from the parent class. Certain methods and attributes can be redesigned specifically to
fit the child class, which is known as Method Overriding. Polymorphism allows us to access
these overridden methods and attributes that have the same name as the parent class.
Let's look at an example:
Example 4: Method Overriding

from math import pi


class Shape:
def __init__(self, name):
self.name = name

def area(self):
pass

def fact(self):
return "I am a two-dimensional shape."

def __str__(self):
return self.name

class Square(Shape):
def __init__(self, length):
super().__init__("Square")
self.length = length

def area(self):
return self.length**2

def fact(self):
return "Squares have each angle equal to 90 degrees."

class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius

Page 142
PYTHON PROGRAMMING KG College of Arts and Science
def area(self):
return pi*self.radius**2

a = Square(4)
b = Circle(7)
print(b)
print(b.fact())
print(a.fact())
print(b.area())
Output
Circle
I am a two-dimensional shape.
Squares have each angle equal to 90 degrees.
153.93804002589985

Here, can see that the methods such as __str__() , which have not been overridden in the child
classes, are used from the parent class.
Due to polymorphism, the Python interpreter automatically recognizes that the fact() method
for object a (Square class) is overridden. So, it uses the one defined in the child class.
On the other hand, since the fact() method for object b isn't overridden, it is used from the
Parent Shape class.

Polymorphism in parent and child classes in Python


Note: Method Overloading, a way to create multiple methods with the same name but different
arguments, is not possible in Python.

Overview of OOP Terminology :


 Class − A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables and
instance variables) and methods, accessed via dot notation.
 Class variable − A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not
used as frequently as instance variables are.
 Data member − A class variable or instance variable that holds data associated with a
class and its objects.

Page 143
PYTHON PROGRAMMING KG College of Arts and Science
 Function overloading − The assignment of more than one behavior to a particular
function. The operation performed varies by the types of objects or arguments involved.
 Instance variable − A variable that is defined inside a method and belongs only to the
current instance of a class.
 Inheritance − The transfer of the characteristics of a class to other classes that are
derived from it.
 Instance − An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the class Circle.
 Instantiation − The creation of an instance of a class.
 Method − A special kind of function that is defined in a class definition.
 Object − A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
 Operator overloading − The assignment of more than one function to a particular
operator.

5.10 SPECIAL METHODS:

Everything in Python is an object and define objects through classes. To define an object,
actually create an instance of a class. Thus, class is the most fundamental piece in Python.
Python‘s special methods (called magic methods).
 The names of these methods begin and end with double underscores (__).
 Suppose t have a simple Word class, and want an equals() method that compares two
words but ignores case.
 That is, a Word containing the value 'kg' would be considered equal to one containing 'KG'.

Classes have:
 Data attributes: Define what is needed to create an instance of a class
 Methods (i.e. procedural attributes): Define how to interact with the instances of a class

Own classes using data and procedural attributes can be created and can implement various
functions to customize a class. In addition to the user-defined functions, it is possible to use built-
in Python function within user-defined classes. This is what special (or magic) methods are for.

Special methods allow for using the built-in Python functions to enrich user-defined classes.
Consider the print function which is one of the most commonly used Python function. To print an
instance of the class, it will print out something like the following:
<__main__.Book object at 0x7f9ed5b1d590>
It displays the name of the class (Book) and the memory location of the object which is not a
proper use of the print function. Can customize its behavior by implementing the __str__ special
method in our class.
#Example
>>> class Word():
def __init__(self, text):
self.text = text
def __eq__(self, word2):
return self.text.lower() == word2.text.lower()
Let‘s see if it works:
>>> first = Word('kg')
Page 144
PYTHON PROGRAMMING KG College of Arts and Science
>>> second = Word('KG‘)
>>> third = Word('eh')
>>> first == second
True
>>> first == third

4 special methods that will be likely to use in the classes.

1. __init__

The __init__ special method is automatically executed when an instance of class is created. It is
also called class constructor. The parameters of the __init__ represent the data attributes of a
class.
Let‘s create a class called Book.

class Book(): def __init__(self, name, writer, pages):

self.name = name

self.writer = writer

self.pages = pages

The self refers to the instance itself. The Book class has 3 data attributes that need to be specified
when creating a Book instance.

b = Book("Moby Dick", "Herman Melville", "378")type(b)


__main__.Book

The variable b is an instance of the Book class.

2. __str__

use the __str__ special method to implement the built-in print function within our class. Without
the __str__, here is what print function does.
print(b)
<__main__.Book object at 0x7f9ed5b1d590>
Let‘s define the __str__ method in our class definition.
def __str__(self):

return f"The title of the book is {self.name}"

Now the print function will return the title of the name. It accesses the name of the book through
the name attribute. can customize it in any way

print(b)
The title of the book is Moby Dick

3. __len__

Page 145
PYTHON PROGRAMMING KG College of Arts and Science
The len function returns the length of an object. For strings, it returns the number of characters.
For a Pandas data frame, it returns the number of row. Can customize its behavior by
implementing the __len__ special method in our class definition. Let‘s make it to return the
number of pages of a book object.
If the __len__ is not implemented in the class definition, you will get an error if you try to use
it on an object of your class. It does not have a default behavior like the print function.

def __len__(self):

return int(self.pages)

len(b)
378
Please note that each time a new function is added to the class, need to recreate the object to be
able to use the new functions.

4. __eq__

The __eq__ special method allows for comparing two instances of a class. If it is defined in the
class, can check if an instance is equal to another instance. The equality condition is specified
using the __eq__ method.
In this case, can declare two books being equal if the names and writers of the book are the
same. They might have different number of pages.

def __eq__(self, other):


return (self.name == other.name) & (self.writer == other.writer)

The ―==‖ operator will return True if both names and writes are the same for two instances. Let‘s
create two books and check if they are equal.

b = Book("Moby Dick", "Herman Melville", "378")


a = Book("Moby Dick", "Herman Melville", "410")
b == a
True
If either names or writes is different, the equality operator returns False.

b = Book("Moby Dick", "Herman Melville", "378")a = Book("Moby Dick", "Melville", "410")


b == a
False

5.10.1 OTHER SPECIAL METHODS :

Table SP. lists special methods that objects must implement to emulate numbers. Mathematical
operations are always evaluated from left to right; when an expression such as x + y appears,
the interpreter tries to invoke the method x.__add__(y). The special methods beginning with r
support operations with reversed operands. These are invoked only if the left operand doesn‘t
implement the specified operation. For example, if x in x + y doesn‘t support
the __add__() method, the interpreter tries to invoke the method y.__radd__(x).

Table SP: Methods for Mathematical Operations


Method Result
__add__(self,other) self + other
Page 146
PYTHON PROGRAMMING KG College of Arts and Science
__sub__(self,other) self – other
__mul__(self,other) self * other
__div__(self,other) self / other
__truediv__(self,other) self / other (future)
__floordiv__(self,other) self // other
__mod__(self,other) self % other
__divmod__(self,other) divmod(self,other)
__pow__(self,other [,modulo]) self ** other, pow(self, other, modulo)
__lshift__(self,other) self << other
__rshift__(self,other) self >> other
__and__(self,other) self & other
__or__(self,other) self | other
__xor__(self,other) self ^ other
__radd__(self,other) other + self
__rsub__(self,other) other - self
__rmul__(self,other) other * self
__rdiv__(self,other) other / self
__rtruediv__(self,other) other / self (future)
__rfloordiv__(self,other) other // self
__rmod__(self,other) other % self
__rdivmod__(self,other) divmod(other,self)
__rpow__(self,other) other ** self
__rlshift__(self,other) other << self
__rrshift__(self,other) other >> self
__rand__(self,other) other & self
__ror__(self,other) other | self
__rxor__(self,other) other ^ self
__iadd__(self,other) self += other
__isub__(self,other) self -= other
__imul__(self,other) self *= other
__idiv__(self,other) self /= other
__itruediv__(self,other) self /= other (future)
__ifloordiv__(self,other) self //= other
__imod__(self,other) self %= other
__ipow__(self,other) self **= other
__iand__(self,other) self &= other
Method Result
__ior__(self,other) self |= other
__ixor__(self,other) self ^= other
__ilshift__(self,other) self <<= other
__irshift__(self,other) self >>= other
__neg__(self) –self
__pos__(self) +self
__abs__(self) abs(self)
__invert__(self) ~self
__int__(self) int(self)
__long__(self) long(self)
__float__(self) float(self)
__complex__(self) complex(self)
Page 147
PYTHON PROGRAMMING KG College of Arts and Science
__oct__(self) oct(self)
__hex__(self) hex(self)
__coerce__(self,other) Type coercion

The methods __iadd__(), __isub__(), and so forth are used to support in-place arithmetic
operators such as a+=b and a-=b (also known as augmented assignment). A distinction is made
between these operators and the standard arithmetic methods because the implementation of the
in-place operators might be able to provide certain customizations such as performance
optimizations. For instance, if the self parameter is not shared, it might be possible to modify its
value in place without having to allocate a newly created object for the result.

The three flavors of division operators, __div__(), __truediv__(),


and __floordiv__(), are used to implement true division (/) and truncating division (//)
operations. The separation of division into two types of operators is a relatively recent change to
Python that was started in Python 2.2, but which has far-reaching effects. As of this writing, the
default behavior of Python is to map the / operator to __div__(). In the future, it will be
remapped to __truediv__(). This latter behavior can currently be enabled as an optional
feature by including the statement from __future__ import division in a program.
The conversion methods __int__(), __long__(), __float__(),
and __complex__() convert an object into one of the four built-in numerical types.
The __oct__() and __hex__() methods return strings representing the octal and hexadecimal
values of an object, respectively.
Comparison Operations
Table lists special methods that objects can implement to provide individualized versions of the
relational operators (<, >, <=, >=, ==, !=). These are known as rich comparisons. Each of these
functions takes two arguments and is allowed to return any kind of object, including a Boolean
value, a list, or any other Python type. For instance, a numerical package might use this to
perform an element-wise comparison of two matrices, returning a matrix with the results. If a
comparison can‘t be made, these functions may also raise an exception.

Table: Methods for Comparisons


Method Result
__lt__(self,other) self < other
__le__(self,other) self <= other
__gt__(self,other) self > other
__ge__(self,other) self >= other
__eq__(self,other) self == other
__ne__(self,other) self != other

By using the above special methods or magic methods or dunder methods can be utilised
efficiently for classes or for programming.

5.11 type() FUNCTION:


Python type() returns the type of the specified object if a single argument is passed to the type().
If three arguments are passed, it returns a new type of object. The type() function either returns
the type of the object or returns a new type object based on the arguments passed.
Signature :
type(object,bases,dict)

Page 148
PYTHON PROGRAMMING KG College of Arts and Science
Parameters
object: The type() returns the type of this object if one parameter is specified.
bases (optional): It specifies the base classes.
dict (optional): It specifies the namespace with the definition for the class.
Return
It returns the type of the specified object if a single argument is passed to the type(). If three
arguments are passed, it returns a new type of object.

#Python type() Function Example 1


#The below example shows how to get the type of an object.
List = [4, 5]
print(type(List))

Dict = {4: 'four', 5: 'five'}


print(type(Dict))

class Python:
a=0

InstanceOfPython = Python()
print(type(InstanceOfPython))
Output:
<class 'list'>
<class 'dict'>
<class '__main__.Python'>
Explanation: In the above example, we have taken a List that contains some values, and in
return, it prints the type of the List.
In the second case, we have taken a Dict that contains some values, and in return, it prints the
type of the Dict.
Then, defined a class named as Python and produced an InstanceOfPython which prints its type.

# Python3 simple code to explain the type() function


print(type([]) is list)
print(type([]) is not list)
print(type(()) is tuple)
print(type({}) is dict)
print(type({}) is not list)
The type() function either returns the type of the object or returns a new type object based on
the arguments passed.
#Example
prime_numbers = [2, 3, 5, 7]

# check type of prime_numbers


result = type(prime_numbers)

print(result)

# Output: <class 'list'>

type() Syntax
The type() function has two different forms:
# type with single parameter
Page 149
PYTHON PROGRAMMING KG College of Arts and Science
type(object)
# type with 3 parameters
type(name, bases, dict)

type() Parameters
The type() function either takes a single object parameter.
Or, it takes 3 parameters
 name - a class name; becomes the __name__ attribute
 bases - a tuple that itemizes the base class; becomes the __bases__ attribute
 dict - a dictionary which is the namespace containing definitions for the class body;
becomes the __dict__ attribute
type() Return Value
The type() function returns type of the object, if only one object parameter is passed a new
type, if 3 parameters passed
Example 1: type() with Object parameter
numbers_list = [1, 2]
print(type(numbers_list))

numbers_dict = {1: 'one', 2: 'two'}


print(type(numbers_dict))
class Foo:
a=0
foo = Foo()
print(type(foo))
Output
<class 'list'>
<class 'dict'>
<class '__main__.Foo'>
To check the type of an object, it is better to use the Python isinstance() function instead. It's
because the isinstance() function also checks if the given object is an instance of the subclass.

#Example 2: type() With 3 Parameters


o1 = type('X', (object,), dict(a='Foo', b=12))
print(type(o1))
print(vars(o1))

class test:
a = 'Foo'
b = 12

o2 = type('Y', (test,), dict(a='Foo', b=12))


print(type(o2))
print(vars(o2))
Output :
<class 'type'>
{'a': 'Foo', 'b': 12, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'X' objects>,
'__weakref__': <attribute '__weakref__' of 'X' objects>, '__doc__': None}
<class 'type'>
{'a': 'Foo', 'b': 12, '__module__': '__main__', '__doc__': None}

Page 150
PYTHON PROGRAMMING KG College of Arts and Science
In the program, have used the Python vars() function which returns
the __dict__ attribute. __dict__ is used to store object's writable attributes. can easily change
these attributes if necessary. For example, to change the __name__ attribute of o1 to 'Z' , use:

o1.__name = 'Z'

ANOTHER EXAMPLE :
# Python3 code to explain the type() function Class of type dict
class DictType:
DictNumber = {1:'John', 2:'Wick', 3:'Barry', 4:'Allen'}

# Class of type list


class ListType:
ListNumber = [1, 2, 3, 4, 5]

# Creating object of each class


d = DictType()
l = ListType()

# Will print accordingly whether both the objects are of same type or not
if type(d) is not type(l):
print("Both class have different object type.")
else:
print("Same Object type")

5.12. REGULAR EXPRESSIONS :


What is Regular Expression in Python?
A Regular Expression (RE) in a programming language is a special text string used for
describing a search pattern. It is extremely useful for extracting information from text such as
code, files, log, spreadsheets or even documents.
While using the Python regular expression the first thing is to recognize is that everything is
essentially a character, and are writing patterns to match a specific sequence of characters also
referred as string. ASCII or latin letters are those that are on your keyboards and Unicode is used
to match the foreign text. It includes digits and punctuation and all special characters like
$#@!%, etc.
For instance, a Python regular expression could tell a program to search for specific text from the
string and then to print out the result accordingly. Expression can include
 Text matching
 Repetition
 Branching
 Pattern-composition etc.
Regular expression or RegEx in Python is denoted as RE (REs, regexes or regex pattern) are
imported through re module. Python supports regular expression through libraries. RegEx in
Python supports various things like Modifiers, Identifiers, and White space characters.
A regular expression is a special sequence of characters that helps you match or find other
strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are
widely used in UNIX world. The Python module re provides full support for Perl-like regular
Page 151
PYTHON PROGRAMMING KG College of Arts and Science
expressions in Python. The re module raises the exception re.error if an error occurs while
compiling or using a regular expression.
Two important functions, which would be used to handle regular expressions. But a small thing
first: There are various characters, which would have special meaning when they are used in
regular expression. To avoid any confusion while dealing with regular expressions, we would
use Raw Strings as r'expression'.
The match Function :
This function attempts to match RE pattern to string with optional flags.
Here is the syntax for this function −
re.match(pattern, string, flags=0)
Regular Expression(RE) Syntax :
import re
 ―re‖ module included with Python primarily used for string searching and manipulation
 Also used frequently for web page ―Scraping‖ (extract large amount of data from
websites)
using the expressions (w+) and (^) :
Example of w+ and ^ Expression
 “^”: This expression matches the start of a string
 “w+―: This expression matches the alphanumeric character in the string
Here Python RegEx Example and how to use w+ and ^ expression in the code. For example, for
string ―is , education is fun‖ execute the code with w+ and^, it will give the output ―is‖.
import re
xx = "is,education is fun"
r1 = re.findall(r"^\w+",xx)
print(r1)

Remember, if you remove +sign from the w+, the output will change, and it will only give the
first character of the first letter, i.e., [g]

Example of \s expression in re.split function


 ―s‖: This expression is used for creating a space in the string
To understand how this RegEx in Python works, begin with a simple Python RegEx Example of
a split function. In the example, split each word using the ―re.split‖ function and at the same time
have used expression \s that allows to parse each word in the string separately.
When this code is executed it will give the output [‗we‘, ‗are‘, ‗splitting‘, ‗the‘, ‗words‘].
Now, let see what happens if ―\‖ is removed from s. There is no ‗s‘ alphabet in the output, this
is because have removed ‗\‘ from the string, and it evaluates ―s‖ as a regular character and thus
split the words wherever it finds ―s‖ in the string.
Similarly, there are series of other Python regular expression that can be of use in various ways
in Python like \d,\D,$,\.,\b, etc.
Here is the complete code
import re
xx = "guru99,education is fun"
r1 = re.findall(r"^\w+", xx)
print((re.split(r'\s','we are splitting the words')))
print((re.split(r's','split the words')))

5.12.1 Using regular expression methods


The ―re‖ package provides several methods to actually perform queries on an input string.
Methods of re in Python:
 re.match()
 re.search()

Page 152
PYTHON PROGRAMMING KG College of Arts and Science
 re.findall()
Note: Based on the regular expressions, Python offers two different primitive operations. The
match method checks for a match only at the beginning of the string while search checks for a
match anywhere in the string.
i)re.match()
re.match() function of re in Python will search the regular expression pattern and return the first
occurrence. The Python RegEx Match method checks for a match only at the beginning of the
string. So, if a match is found in the first line, it returns the match object. But if a match is found
in some other line, the Python RegEx Match function returns null.
For example, consider the following code of Python re.match() function. The expression ―w+‖
and ―\W‖ will match the words starting with letter ‗g‘ and thereafter, anything which is not
started with ‗g‘ is not identified. To check match for each element in the list or string, we run the
forloop in this Python re.match() Example.
ii)re.search(): Finding Pattern in Text
re.search() function will search the regular expression pattern and return the first occurrence.
Unlike Python re.match(), it will check all lines of the input string. The Python re.search()
function returns a match object when the pattern is found and ―null‖ if the pattern is not found
In order to use search() function, you need to import Python re module first and then execute the
code. The Python re.search() function takes the ―pattern‖ and ―text‖ to scan from our main string
For example here look for two literal strings ―Software testing‖ ―guru99‖, in a text string
―Software Testing is fun‖. For ―software testing‖ found the match hence it returns the output of
Python re.search() Example as ―found a match‖, while for word ―guru99‖ could not found in
string hence it returns the output as ―No match‖.

iii)re.findall()
findall() module is used to search for ―all‖ occurrences that match a given pattern. In contrast,
search() module will only return the first occurrence that matches the specified pattern. findall()
will iterate over all the lines of the file and will return all non-overlapping matches of pattern in
a single step.
For example, here we have a list of e-mail addresses, and we want all the e-mail addresses to be
fetched out from the list, we use the method re.findall() in Python. It will find all the e-mail
addresses from the list.

import re

list = ["guru99 get", "guru99 give", "guru Selenium"]


for element in list:
z = re.match("(g\w+)\W(g\w+)", element)
if z:
print((z.groups()))

patterns = ['software testing', 'guru99']


text = 'software testing is fun?'
for pattern in patterns:
print('Looking for "%s" in "%s" ->' % (pattern, text), end=' ')
if re.search(pattern, text):
print('found a match!')
else:
print('no match')
abc='guru99@google.com,careerguru99@hotmail.com, users@yahoomail.com'
emails = re.findall(r'[\w\.-]+@[\w\.-]+', abc)
for email in emails:
print(email) Page 153
PYTHON PROGRAMMING KG College of Arts and Science

5.13.CHARACTER CLASS
A "character class", or a "character set", is a set of characters put in square brackets. The
regex engine matches only one out of several characters in the character class or character set.
Place the characters where it is needed to match between square brackets. To match any vowel,
use the character set [aeiou]. A character class or set matches only a single character. The order
of the characters inside a character class or set does not matter. The results are identical. use a
hyphen inside a character class to specify a range of characters. [0-9] matches a single digit
between 0 and 9. Similarly for uppercase and lowercase letters we have the character class [A-
Za-z]

#Example
The following code finds and prints all the vowels in the given string
import re
s = 'mother of all battles'
result = re.findall(r'[aeiou]', s)
print result
Output
This gives the output
['o', 'e', 'o', 'a', 'a', 'e']

5.14 CHARACTERS AND CHARACTER CLASSES


The simplest expressions are just literal characters, such as a or 5, and if no quantifier is
explicitly given the expression is taken to be "match one occurrence." For example, the
regex tune consists of four expressions, each implicitly quantified to match once, so it matches
one t followed by one u followed by one n followed by one e, and hence matches the
strings tune and attuned.
Although most characters can be used as literals, some are special characters—symbols in
the regex language that must be escaped by preceding them with a backslash (\) to use them as
literals. The special characters are \.^$?+*{}[]()|. Most of Python's standard string escapes
can also be used within regexes; for example, \n for newline and \t for tab, as well as
hexadecimal escapes for characters using the \xHH, \uHHHH, and \UHHHHHHHH syntaxes.
In many cases, rather than matching one particular character we want to match any one of a set
of characters. This can be achieved by using a character class—one or more characters enclosed
in square brackets.
A character class is an expression. Like any other expression, if not explicitly quantified it
matches exactly one character (which can be any of the characters in the character class). For
example, the regex r[ea]d matches both red and radar, but not read. Similarly, to match a
single digit we can use the regex [0123456789]. For convenience we can specify a range of
characters using a hyphen, so the regex [0-9] also matches a digit. It's possible to negate the
meaning of a character class by following the opening bracket with a caret, so [^0-9] matches
any character that is not a digit.
Inside a character class, apart from the backslash (\), the special characters lose their special
meaning, although the caret (^) acquires a new meaning (negation) if it's the first character in the
character class, and otherwise is simply a literal caret. Also, the hyphen ( -) signifies a character

Page 154
PYTHON PROGRAMMING KG College of Arts and Science
range unless it's the first character, in which case it's a literal hyphen. Since some sets of
characters are required so frequently, several have shorthand forms, which are shown in Table 1.
With one exception, the shorthands can be used inside character sets; for example, the
regex [\dA-Fa-f] matches any hexadecimal digit. The exception is the period (.) which is a
shorthand outside a character class but matches a literal period inside a character class.
Table 1 Character Class Shorthands
Symbol Meaning
. Matches any character except newline, any character at all with the re.DOTALL flag, or
inside a character class matches a literal period.
\d Matches a Unicode digit, or [0-9] with the re.ASCII flag.
\D Matches a Unicode nondigit, or [^0-9] with the re.ASCII flag.
\s Matches a Unicode whitespace, or [ \t\n\r\f\v] with the re.ASCII flag.
\S Matches a Unicode non-whitespace, or [^ \t\n\r\f\v] with the re.ASCII flag.
\w Matches a Unicode "word" character, or [a-zA-Z0-9_] with the re.ASCII flag.
\W Matches a Unicode non-"word" character, or [^a-zA-Z0-9_] with the re.ASCII flag.

5.15.QUANTIFIERS IN REGULAR EXPRESSIONS :

Quantifiers specify how many instances of a character, group, or character class must be
present in the input for a match to be found. A quantifier has the form {m,n} where m and n are
the minimum and maximum times the expression to which the quantifier applies must match.
For example, both e{1,1}e{1,1} and e{2,2} match feel, but neither matches felt. Writing a
quantifier after every expression would soon become tedious, and is certainly difficult to read.
Regex language supports several convenient shorthands. If only one number is given in
the quantifier, it's taken to be both the minimum and the maximum, so e{2} is the same
as e{2,2}. As noted in the preceding section, if no quantifier is explicitly given, it's assumed to
be 1 (that is, {1,1} or {1}); therefore, ee is the same as e{1,1}e{1,1} and e{1}e{1}, so
both e{2} and ee match feel but not felt.
Having a different minimum and maximum is often convenient. For example, to
match travelled and traveled (both legitimate spellings),we could use
either travel{1,2}ed or travell{0,1}ed. The {0,1} quantification is used so often that it has its
own shorthand form, ?, so another way of writing the regex (and the one most likely to be used
in practice) is travell?ed.
Two other quantification shorthands are provided: A plus sign (+) stands for {1,n} ("at least
one") and an asterisk (*) stands for {0,n} ("any number of"). In both cases, n is the maximum
possible number allowed for a quantifier, usually at least 32767. Table 2 shows all the
quantifiers.
The + quantifier is very useful. For example, to match integers, could use \d+ to match one or
more digits. This regex could match in two places in the string 4588.91, for
example: 4588.91 and 4588.91. Sometimes typos are the result of pressing a key too long. We
could use the regex bevel+ed to match the legitimate beveled and bevelled, and the
incorrect bevellled. If we wanted to standardize on the single-l spelling, and match only oc
Table 2 Regular Expression Quantifiers
Syntax Meaning
e? or e{0,1} Greedily match zero occurrences or one occurrence of expression e.
e?? or e{0,1}? Nongreedily match zero occurrences or one occurrence of expression e.
e+ or e{1,} Greedily match one or more occurrences of expression e.
e+? or e{1,}? Nongreedily match one or more occurrences of expression e.
e* or e{0,} Greedily match zero or more occurrences of expression e.
e*? or e{0,}? Nongreedily match zero or more occurrences of expression e.
e{m} Match exactly m occurrences of expression e.
Page 155
PYTHON PROGRAMMING KG College of Arts and Science
e{m,} Greedily match at least m occurrences of expression e.
e{m,}? Nongreedily match at least m occurrences of expression e.
e{,n} Greedily match at most n occurrences of expression e.
e{,n}? Nongreedily match at most n occurrences of expression e.
e{m,n} Greedily match at least m and at most n occurrences of expression e.
e{m,n}? Nongreedily match at least m and at most n occurrences of expression e.

5.16 THE WILDCARD CHARACTER/DOT CHARACTER:


The period . (or dot) character in regex is called a wildcard because it matches any
character except for a newline.
#Example : Implementing Wildcard
atRegex = re.compile(r‘.at‘)
# returns anything with ‗at‘ followed
afteratRegex.findall(‗The cat in the hat sat on the flat mat‘)# return: [‗cat‘, ‗hat‘, ‗sat‘, ‗lat‘,
‗mat‘]

the dot character will match just one character, which is why the match for the text ―flat‖
in this example matched only ―lat‖. To match an actual dot, escape the dot with a backslash: \
#Ex- Wildcard with Repetition
atRegex = re.compile(r’.{1,2}at’)
With regard to {1, 2}, it means any 1 or 2 characters (even white spaces), followed by ―at‖.
Matching Everything with Dot-Star
#Example : Implementing Dot-Star
The dot-star (.*) uses greedy mode. It will always try to match as much text as possible. To
match any and all text in a non-greedy fashion, use the dot, star, and question mark (.*?).
Similarly with braces, the question mark tells Python to match in a non-greedy way.

5.18 SPECIAL CHARACTERS


A special characteror sequence is a \ followed by one of the characters in the list below, and has
a special meaning: Character Description Example \A Returns a match if the specified characters
are at the beginning of the string "\AThe" \b Returns a match where the specified characters are
at the beginning or at the r"\bain" end of a word r"ain\b" \B Returns a match where the specified
characters are present, but NOT at the beginning (or at the end) of a word (the "r" in the
beginning is making sure that the string is being treated as a "raw string") r"\Bain" r"ain\B" \d
Returns a match where the string contains digits (numbers from 0-9) "\d" \D Returns a match
where the string DOES NOT contain digits "\D" \s Returns a match where the string contains a
white space character "\s" \S Returns a match where the string DOES NOT contain a white space
character "\S" \w Returns a match where the string contains any word characters (characters
from a to Z, digits from 0-9, and the underscore _ character) "\w" \W Returns a match where the
string DOES NOT contain any word characters "\W" \Z Returns a match if the specified
characters are at the end of the string "Spain\Z"

The + symbol used after the \d in the example above is used for repetition. You will see this in
some more detail in the repetition section later on...

\t - Lowercase t. Matches tab.


\n - Lowercase n. Matches newline.

Page 156
PYTHON PROGRAMMING KG College of Arts and Science
\r - Lowercase r. Matches return.
\A - Uppercase a. Matches only at the start of the string. Works across multiple lines as well.
\Z - Uppercase z. Matches only at the end of the string.
TIP: ^ and \A are effectively the same, and so are $ and \Z. Except when dealing with

5.19 GROUPING IN REGULAR EXPRESSIONS


The group feature of regular expression allows you to pick up parts of the matching text. Parts of
a regular expression pattern bounded by parenthesis () are called groups. The parenthesis does
not change what the expression matches, but rather forms groups within the matched sequence.
Using the group() function all along in this tutorial's examples. The plain match.group() without
any argument is still the whole matched text as usual.

Let's understand this concept with a simple example. Imagine you were validating email
addresses and wanted to check the user name and host. This is when you would want to create
separate groups within your matched text.

statement = 'Please contact us at: [email protected]'


match = re.search(r'([\w\.-]+)@([\w\.-]+)', statement)
if statement:
print("Email address:", match.group()) # The whole matched text
print("Username:", match.group(1)) # The username (group 1)
print("Host:", match.group(2)) # The host (group 2)
Email address: [email protected]
Username: support
Host: datacamp.com

Another way of doing the same is with the usage of <> brackets instead. This will let you create
named groups. Named groups will make your code more readable. The syntax for creating
named group is: (?P<name>...). Replace the name part with the name you want to give to your
group. The ... represent the rest of the matching syntax. See this in action using the same
example as before...

statement = 'Please contact us at: [email protected]'


match = re.search(r'(?P<email>(?P<username>[\w\.-]+)@(?P<host>[\w\.-]+))', statement)
if statement:
print("Email address:", match.group('email'))
print("Username:", match.group('username'))
print("Host:", match.group('host'))
Email address: [email protected]
Username: support
Host: datacamp.com

5.20 GREEDY MATCHES


A greedy match means that the regex engine (the one which tries to find your pattern in the
string) matches as many characters as possible. For example, the regex 'a+' will match as many
'a' s as possible in your string 'aaaa'.
#Example
>>> import re
>>> re.findall('a?', 'aaaa')
['a', 'a', 'a', 'a', '']
>>> re.findall('a*', 'aaaa')
['aaaa', '']
Page 157
PYTHON PROGRAMMING KG College of Arts and Science
>>> re.findall('a+', 'aaaa')
['aaaa']
>>> re.findall('a{3}', 'aaaa')
['aaa']
>>> re.findall('a{1,2}', 'aaaa')
['aa', 'aa']

In all cases, a shorter match would also be valid. But as the regex engine is greedy per default,
those are not enough for the regex engine.

5.21 MATCH OBJECT


A Match Object is an object containing information about the search and the result. Example
Do a search that will return a Match Object: import re txt = "The rain in Spain" x = re.search("ai",
txt) print(x) #this will print an object Output: The Match object has properties and methods used
to retrieve information about the search, and the result: .span() returns a tuple containing the
start-, and end positions of the match. .string returns the string passed into the function .group()
returns the part of the string where there was a match
Example Print the position (start- and end-position) of the first match occurrence. The regular
expression looks for any words that starts with an upper case "S":
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span())
#Ouput:
(12, 17)

#Example Print the string passed into the function:


import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string)
#Output:
The rain in Spain

5.21 GROUPING
Example Print the part of the string where there was a match. The regular expression looks for
any words that starts with an upper case "S":
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group())
#Output:
Spain
The search() Function The search() function searches the string for a match, and returns a
Match object if there is a match. If there is more than one match, only the first occurrence of the
match will be returned: Example txt = "The rain in Spain" x = re.search("\s", txt) print("The first
white-space character is located in position:", x.start())

Page 158
PYTHON PROGRAMMING KG College of Arts and Science
5.22 GREEDY VS. NON-GREEDY MATCHING :
When a special character matches as much of the search sequence (string) as possible, it is said
to be a "Greedy Match". It is the normal behavior of a regular expression, but sometimes this
behavior is not desired:

pattern = "cookie"
sequence = "Cake and cookie"

heading = r'<h1>TITLE</h1>'
re.match(r'<.*>', heading).group()
'<h1>TITLE</h1>'
The pattern <.*> matched the whole string, right up to the second occurrence of >.

However, if you only wanted to match the first <h1> tag, you could have used the greedy
qualifier *? that matches as little text as possible.

Adding ? after the qualifier makes it perform the match in a non-greedy or minimal fashion; That
is, as few characters as possible will be matched. When you run <.*>, you will only get a match
with <h1>.

heading = r'<h1>TITLE</h1>'
re.match(r'<.*?>', heading).group()
'<h1>'

5.23 SPLITTING A STRING


The split() function returns a list where the string has been split at each match:
#Example Split at each white-space character:

import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
#o/p
['The', 'rain', 'in', 'Spain']

5.24 SUBSTITUTING
The sub() function replaces the matches with the text of your choice:
#Example Replace every white-space character with the number 9:
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)
o/p
The9rain9in9Spain

#Example
import re
#Replace the first two occurrences of a white-space character with the digit 9:
txt = "The rain in Spain"
x = re.sub("\s", "9", txt, 2)
print(x)
#output
Page 159
PYTHON PROGRAMMING KG College of Arts and Science
The9rain9in Spain

5.25 COMPILING REGULAR EXPRESSIONS


It is possible to combine a regular expression pattern into pattern objects, which can be used for
pattern matching. It also helps to search a pattern again without rewriting it. re.compile(pattern,
repl, string):
#Example
import re
pattern=re.compile('TP')
result=pattern.findall('TP Tutorialspoint TP')
print result
result2=pattern.findall('TP is most popular tutorials site of India')
print result2
#Output
['TP', 'TP'] ['TP']
SUMMARY :

It is a lot of information and concepts to grasp! The following table summarizes all

Character(s) What it does


. A period. Matches any single character except the newline character.
^ A caret. Matches a pattern at the start of the string.
\A Uppercase A. Matches only at the start of the string.
$ Dollar sign. Matches the end of the string.
\Z Uppercase Z. Matches only at the end of the string.
[] Matches the set of characters you specify within it.
\ ∙ If the character following the backslash is a recognized escape character, then the
special meaning of the term is taken.
∙ Else the backslash () is treated like any other character and passed through.
∙ It can be used in front of all the metacharacters to remove their special meaning.
\w Lowercase w. Matches any single letter, digit, or underscore.
\W Uppercase W. Matches any character not part of \w (lowercase w).
\s Lowercase s. Matches a single whitespace character like: space, newline, tab, return.
\S Uppercase S. Matches any character not part of \s (lowercase s).
\d Lowercase d. Matches decimal digit 0-9.
\D Uppercase D. Matches any character that is not a decimal digit.
\t Lowercase t. Matches tab.
\n Lowercase n. Matches newline.
\r Lowercase r. Matches return.
\b Lowercase b. Matches only the beginning or end of the word.
+ Checks if the preceding character appears one or more times.
* Checks if the preceding character appears zero or more times.
? ∙ Checks if the preceding character appears exactly zero or one time.
∙ Specifies a non-greedy version of +, *
{} Checks for an explicit number of times.
() Creates a group when performing matches.
<> Creates a named group when performing matches.
END OF UNIT 5
END OF ALL 5 UNITS

Page 160

You might also like