All 5 Units-Python Programming
All 5 Units-Python Programming
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
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
Page 4
PYTHON PROGRAMMING KG College of Arts and Science
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
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 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.
Page 9
PYTHON PROGRAMMING KG College of Arts and Science
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.
Page 12
PYTHON PROGRAMMING KG College of Arts and Science
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).
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‘>
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.8 COMMENTS:
Page 15
PYTHON PROGRAMMING KG College of Arts and Science
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 '''
# 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:
>>> "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
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'
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.
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.
>>> 5 + 6 11
>>> import operator
>>> operator.add(5, 6) 11
>>> operator.__add__(5, 6) 11
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
Page 20
PYTHON PROGRAMMING KG College of Arts and Science
ASSIGNMENT OPERATORS:
The assignment operators are used to assign values to variables. The following
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
Page 23
PYTHON PROGRAMMING KG College of Arts and Science
BITWISE OPERATORS
& 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.
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
#Another Example
# Python program showing how to multiple input using #split (ie) taking two inputs at a time
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.
#Example:
# This line will automatically add a new line before the # next print statement
# This print() function ends with "**" as set in the end argument.
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&
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
>>> x = 5; y = 10
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
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.
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").
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
\' 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:
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
#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:
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
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
Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/dic.py Keys are:
ces it ece
Values are:
block1 block2 block3
statements statements
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
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
Output:
11
9
88
The number 88 is found
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:
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]:
Output:
C:/Users/KGCAS/AppData/Local/Programs/Python/Python38-32/pyyy/cont2.py 11
9
89
Page 42
PYTHON PROGRAMMING KG College of Arts and Science
L[-2] college Negative: count from the right
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()
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.
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).
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
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()
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()
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
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
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
# Example
def greet(name):
print ('Hello ', name)
greet('students') # calling function with argument
greet(123)
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
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
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
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
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
#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.
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.
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)
#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 = []
A set is an unordered sequence of items that you have to put inside braces ({ }). In a set,
you can't have duplicate items.
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.
•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)
There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.
Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint get
while the users who are still learning Python:
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 :
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo
>>> 4 + spam*3
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
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..."
...
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:
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):
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:
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:
Page 80
PYTHON PROGRAMMING KG College of Arts and Science
>>> try:
... this_fails()
... except ZeroDivisionError, detail:
... print ‘Handling run-time error:‘, detail
...
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!")
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.
The raise statement allows the programmer to force a specified exception to occur. For example:
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
...
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:
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
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!
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.
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 :
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.
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 –
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
Page 88
PYTHON PROGRAMMING KG College of Arts and Science
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.
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
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
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')
#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:
can read a file line-by-line using a for loop. This is both efficient and fast.
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
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
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.
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())
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
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()
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.
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
#Example
import os
os.chdir("C:\cas\ct")
>>> 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']
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()
[]
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.
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:
.'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.
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:
'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.
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).
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()
Return Type: This method returns a pair of file descriptors (r, w) usable for reading and writing,
respectively.
# 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()
else:
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
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...
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.
Page 113
PYTHON PROGRAMMING KG College of Arts and Science
# importing os module
import os
# Path
path = "./mypipe"
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)
In the above example, have created a class named dog using the class keyword.
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.
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:
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"
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!
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
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.
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)
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.
# Class variables
animal_type = "fish"
location = "ocean"
def main():
# First object, set up instance variables of constructor method
sammy = Shark("Sammy", 5)
# Second object
stevie = Shark("Stevie", 8)
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.
# Instance method
def description(self):
return f"{self.name} is {self.age} years old"
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'
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:
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 __str__(self):
return f"{self.name} is {self.age} years old"
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
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))
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.
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.
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.
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
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"):
ob = Child3()
ob.func1()
Page 133
PYTHON PROGRAMMING KG College of Arts and Science
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.
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.
#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.
>>>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.
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.
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.
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.
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.
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")
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.
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
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.
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.
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
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.
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.
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):
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.
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.
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).
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.
By using the above special methods or magic methods or dunder methods can be utilised
efficiently for classes or for programming.
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.
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.
print(result)
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))
class test:
a = 'Foo'
b = 12
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'}
# 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")
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]
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
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']
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.
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.
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.
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...
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
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.
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...
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 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>'
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
It is a lot of information and concepts to grasp! The following table summarizes all
Page 160