Python
Python
Python supports multiple programming pattern, including object oriented, imperative and
functional or procedural programming styles. Python is not intended to work on special area
such as web programming. That is why it is known as multipurpose because it can be used with
web, enterprise, 3D CAD etc. Python makes the development and debugging fast because there
is no compilation step included in python development and edit-test-debug cycle is very fast.
Python History
Python Features
Python provides lots of features that are listed below.
1) Easy to Learn and Use : Python is easy to learn and use. It is developer-friendly and high
level programming language.
2) Expressive Language : Python language is more expressive means that it is more
understandable and readable.
3) Interpreted Language : Python is an interpreted language i.e. interpreter executes the code
line by line at a time. This makes debugging easy and thus suitable for beginners.
4) Cross-platform Language : Python can run equally on different platforms such as Windows,
Linux, Unix and Macintosh etc. So, we can say that Python is a portable language.
5) Free and Open Source :Python language is freely available at offical web address. The source-
code is also available. Therefore it is open source.
6) Object-Oriented Language :Python supports object oriented language and concepts of classes
and objects come into existence.
7) Extensible : It implies that other languages such as C/C++ can be used to compile the code
and thus it can be used further in our python code.
8) Large Standard Library : Python has a large and broad library and prvides rich set of module
and functions for rapid application development.
9) GUI Programming Support : Graphical user interfaces can be developed using Python.
10) Integrated : It can be easily integrated with languages like C, C++, JAVA etc.
Python Applications
Python is known for its general purpose nature that makes it applicable in almost each domain of
software development. Python as a whole can be used in any sphere of development. Here, we
are specifing applications areas where python can be applied.
1) Web Applications : We can use Python to develop web applications. It provides libraries to
handle internet protocols such as HTML and XML, JSON, Email processing, request,
beautifulSoup, Feedparser etc. It also provides Frameworks such as Django, Pyramid, Flask etc
to design and delelop web based applications. Some important developments are:
PythonWikiEngines, Pocoo, PythonBlogSoftware etc.
2) Desktop GUI Applications : Python provides Tk GUI library to develop user interface in
python based application. Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on
several platforms. The Kivy is popular for writing multitouch applications.
3) Software Development : Python is helpful for software development process. It works as a
support language and can be used for build control and management, testing etc.
4) Scientific and Numeric : Python is popular and widely used in scientific and numeric
computing. Some useful library and package are SciPy, Pandas, IPython etc. SciPy is group of
packages of engineering, science and mathematics.
5) Business Applications : Python is used to build Bussiness applications like ERP and e-
commerce systems. Tryton is a high level application platform.
6) Console Based Application : We can use Python to develop console based applications. For
example: IPython.
7) Audio or Video based Applications : Python is awesome to perform multiple tasks and can be
used to develop multimedia applications. Some of real applications are: TimPlayer, cplay etc.
8) 3D CAD Applications : To create CAD application Fandango is a real application which
provides full features of CAD.
9) Enterprise Applications : Python can be used to create applications which can be used within
an Enterprise or an Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.
10) Applications for Images : Using Python several application can be developed for image.
Applications developed are: VPython, Gogh, imgSeek etc.
There are several such applications which can be developed using Python
Python programming language is being updated regularly with new features and supports. There
are lots of updations in python versions, started from 1994 to current release.
A list of python versions with its released date is given below.
Python Version Released Date
Python Keywords are special reserved words which convey a special meaning to the
compiler/interpreter. Each keyword have a special meaning and a specific operation. These
keywords can't be used as variable. Following is the List of Python Keywords.
Installing Python
Visit the link https://www.python.org/downloads/ to download the latest release of Python. In
this process, we will install Python 3.6.7 on our Windows operating system.
Double-click the executable file which is downloaded; the following window will open. Select
Customize installation and proceed.
The following window shows all the optional features. All the features need to be installed and
are checked by default; we need to click next to continue.
The following window shows a list of advanced options. Check all the options which you want
to install and click next. Here, we must notice that the first check-box (install for all users) must
be checked.
Now, we are ready to install python-3.6.7. Let's install it.
Now, try to run python on the command prompt. Type the command python in case of python2
or python3 in case of python3. It will show an error as given in the below image. It is because
we haven't set the path.
Environment Variables
To set the path of python, we need to the right click on "my computer" and go to Properties →
Advanced → Environment Variables.
Add the new path variable in the user variable section.
Type PATH as the variable name and set the path to the installation directory of the python
shown in the below image.
Executing Python from the Command Line
Now, the path is set, we are ready to run python on our local system. Restart CMD, and
type python again. It will open the python interpreter shell where we can execute the python
statements. The following screen will appear
To come out from screen press Ctrl Z (^Z) at >>> prompt.
IDLE
Once you have Python installed on your computer, you are ready to work on it. Python works in
two ways
Interactive mode
Script mode
Interactive mode : means you type the command – one command at a time, python executes the
given command and give you the output. In interactive mode you type the command in front of
Python prompt >>>. For example if you type 10+20 in front of Python prompt it will give the
result 30. Search for IDLE in windows or in Run window type IDLE and the following screen
will appear
Click on Start button -> All Programs -> Python -> IDLE(Python GUI)
ii) Python Shell will be opened. Now click on File -> New Window.
Dynamic Types
Python variable assignment is different from some of the popular languages like c, c++ and java.
There is no declaration of a variable, just an assignment statement.
When we declare a variable in C or alike languages, this sets aside an area of memory for
holding values allowed by the data type of the variable. The memory allocated will be interpreted
as the data type suggests. If it’s an integer variable the memory allocated will be read as an
integer and so on. When we assign or initialize it with some value, that value will get stored at
that memory location. At compile time, initial value or assigned value will be checked. So we
cannot mix types. Example: initializing a string value to an int variable is not allowed and the
program will not compile.
But Python is a dynamically typed language. It doesn’t know about the type of the variable until
the code is run. So declaration is of no use. What it does is, It stores that value at some memory
location and then binds that variable name to that memory container. And makes the contents of
the container accessible through that variable name. So the data type does not matter.
Naming Conventions
While working in python, one should keep in mind certain style rules and conversations. In the
following lines, we are giving some very elementary and basic style rules:
1. Statement Termination : Python does not use any symbol to terminate a statement. when
you end a physical code –line by pressing enter key, the statement is considered is
terminated by default.
Exercise :
Very Short Answer Questions
5 What is keyword?
2 What is IDLE?
if True:
print "True"
else:
print "False"
However, the following block generates an error −
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Thus, in Python all the continuous lines indented with same number of spaces would form a
block. The following example has various statement blocks −
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the
line continuation character (\) to denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation
character. For example −
Comments
Comments in Python can be used to explain any program code. It can also be used to hide the
code as well. Comments are the most helpful stuff of any program. It enables us to understand
the way, a program works. In python, any statement written along with # symbol is known as a
comment. The interpreter does not interpret the comment. Comment is not a part of the program,
but it enhances the interactivity of the program and makes the program readable.
Python supports two types of comments:
1) Single Line Comment:
In case user wants to specify a single line comment, then comment must start with ?#?
Eg:
# This is single line comment.
print ("Hello Python" )
Output:
Hello Python
2) Multi Line Comment:
Multi lined comment can be given inside triple quotes.
eg:
''''' This
Is
Multipline comment'''
eg:
#single line comment
print ("Hello Python")
'''''This is
multiline comment'''
Output:
Hello Python
String Values
In python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Consider the following example in python to create a string.
str = "Hi Welcone Python !"
if we check the type of the variable str using a python script
print(type(str)), then it will print string (str).
In python, strings are treated as the sequence of strings which means that python doesn't support
the character data type instead a single character written as 'p' is treated as the string of length 1.
var=’This is a good
example’
Returns the length of given String print (len(var))
len(string) output : 22
Parameter Values
Parameter Description
String Operators
String operators can be used to manipulate the string in multiple ways. Following is the list of
String operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side
of the operator.
* It is known as repetition operator. It concatenates the multiple copies of the
same string.
[] It is known as slice operator. It is used to access the sub-strings of a particular
string.
[:] It is known as range slice operator. It is used to access the characters from the
specified range.
in It is known as membership operator. It returns if a particular sub-string is
present in the specified string.
not in It is also a membership operator and does the exact reverse of in. It returns true
if a particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we
need to print the actual meaning of escape characters such as "C://python". To
define any string as a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers
used in C programming like %d or %f to map their values in python. We will
discuss how formatting is done in python.
Python String operator Example
Str=”Hello”
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output :
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Numeric Data Types
Python numeric data type is used to hold numeric values like
int (signed integers) − They are often called just integers or ints, are positive or negative
whole numbers with no decimal point.
long (long integers ) − Also called longs, they are integers of unlimited size, written like
integers and followed by an uppercase or lowercase L.
float (floating point real values) − Also called floats, they represent real numbers and
are written with a decimal point dividing the integer and fractional parts. Floats may also
be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 10 2 =
250).
complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or
j) represents the square root of -1 (which is an imaginary number). The real part of the
number is a, and the imaginary part is b. Complex numbers are not used much in Python
programming.
In Python we need not to declare datatype while declaring a variable like C or C++. We can
simply just assign values in a variable. But if we want to see what type of numerical value is it
holding right now, we can use type() function.
Python allows you to use a lowercase L with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.
A complex number consists of an ordered pair of real floating point numbers denoted by a + bj,
where a is the real part and b is the imaginary part of the complex number.
Conversion Functions
Python internally changes the data type of some operands so that all operands have same data
type. This type of conversion is called automatic or implicit type conversion. Python also
supports explicit type conversion. It is also known as type casting. It is performed by <data
type>(expression).
Let's see an example where Python promotes conversion of lower datatype (integer) to higher
data type (float) to avoid data loss.
Data conversion integer to float Example 1
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
Output :
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Data Conversion addition of string and integer using explicit conversion Example 2
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
Output :
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>
Simple Output
The simplest way to produce output is using the print() function where you can pass zero or more
expressions separated by commas. This function converts the expressions you pass into a string
before writing to the screen.
Example
print (“hello”) # string to be printed
print(17.5) # float to be printed
print(25) # int to be printed
print(“sum of 2 and 3 is”,2+3) # message and calculation to be printed
Simple Input
The input() method reads a line from input, converts into a string and returns it.
The syntax of input() method is:
input([prompt])
input() Parameters
The input() method takes a single optional argument:
prompt (Optional) - a string that is written to standard output (usually screen) without trailing
newline
Return value from input()
The input() method reads a line from input (usually user), converts the line into a string by
removing the trailing newline, and returns it. If EOF is read, it raises an EOFError exception.
Example 1: How input() works in Python?
# get input from user
inputString = input()
print('The inputted string is:', inputString)
When you run the program, the output will be:
Python is interesting.
The inputted string is: Python is interesting
Example 2: Get input from user with a prompt
# get input from user
inputString = input('Enter a string:')
print('The inputted string is:', inputString)
When you run the program, the output will be:
Enter a string: Python is interesting.
The inputted string is: Python is interesting
The % Method
Python uses C-style string formatting to create new, formatted strings. The "%" operator is used
to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string,
which contains normal text together with "argument specifiers", special symbols like "%s" and
"%d". For string %s and for integer %d is used.
Let's say you have a variable called "name" with your user name in it, and you would then like to
print(out a greeting to that user.)
# This prints out "Hello, Mohan!"
name = "Mohan"
print("Hello, %s!" % name)
Output :
Hello, Mohan
To use two or more argument specifiers, use a tuple (parentheses):
# This prints out "Mohan is 32 years old."
name = "Mohan"
age = 32
print("%s is %d years old." % (name, age))
Output:
Mohan is 32 years old.
Exercise :
Very Short Answer Questions
1. What is string ?
2. What is comment ?
3. What is conversion function ?
4. What is % method ?
5. What is input function ?
Indenting Requirements
Most of the programming languages like C, C++, Java use braces { } to define a block of code.
Python uses indentation. A code block (body of a function, loop etc.) starts with indentation and
ends with the first unindented line. The amount of indentation is up to you, but it must be
consistent throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an
example.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results into
Python programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes
the code more readable. For example:
if True:
print('Hello')
a=5
and
if True: print('Hello'); a = 5
both are valid and do the same thing. But the former style is clearer.
Incorrect indentation will result into IndentationError.
The if Statement
Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.
In python, decision making is performed by the following statements.
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is
true, a block of code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it
Statement also provides the block of the code for the false case of the condition
to be checked. If the condition provided in the if statement is false,
then the else statement will be executed.
Nested if Nested if statements enable us to use if ? else statement inside an outer
Statement if statement.
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.
1. if expression:
2. statement
Example 1 : Program to check even number
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
Output:
enter the number?10
Number is even
Example 2 : Program to print the largest of the three numbers.
a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
Output:
Enter your age? 20
You are eligible to vote !!
Output:
enter the number?10
Number is even
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Output:
Enter the number?15
number is not equal to 10, 50 or 100
Output:
Enter the marks ?95
Congrats ! you scored grade A ...
< If the first operand is less than the second operand, then the condition becomes true.
Output :
False
True
True
False
Logical Operator
The logical operators are used primarily in the expression evaluation to make a decision. Python
supports the following logical operators.
Operator Description
If both the expression are true, then the condition will be true. If a and b are the two
And
expressions, a → true, b → true => a and b → true.
If one of the expressions is true, then the condition will be true. If a and b are the two
Or
expressions, a → true, b → false => a or b → true.
Not If an expression a is true then not (a) will be false and vice versa.
Output :
True
True
False
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the
and) result. Otherwise, 0 is copied.
The resulting bit will be 0 if both the bits are zero otherwise the resulting bit will
| (binary or)
be 1.
^ (binary The resulting bit will be 1 if both the bits are different otherwise the resulting bit
xor) will be 0.
It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting
~ (negation)
bit will be 1 and vice versa.
The left operand value is moved left by the number of bits present in the right
<< (left shift)
operand.
>> (right
The left operand is moved right by the number of bits present in the right operand.
shift)
a=7
b=9
print(a&b)
output :
1
The while Loop
The while loop is also known as a pre-tested loop. In general, a while loop allows a part of the
code to be executed as long as the given condition is true.
It can be viewed as a repeating if statement. The while loop is mostly used in the case where the
number of iterations is not known in advance.
The syntax is given below.
while expression:
statements
Here, the statements can be a single statement or the group of statements. The expression should
be any valid python expression resulting into true or false. The true is any non-zero value.
Example 1
i=1;
while i<=10:
print(i);
i=i+1;
Output:
1
2
3
4
5
6
7
8
9
10
Example 2
i=1
number=0
b=9
number = int(input("Enter the number?"))
while i<=10:
print("%d X %d = %d \n"%(number,i,number*i));
i = i+1;
Output:
Enter the number?10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
break statement
The break is a keyword in python which is used to bring the program control out of the loop. The
break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner
loop first and then proceeds to outer loops. In other words, we can say that break is used to abort
the current execution of the program and the control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition.
The syntax of the break is given below.
#loop statements
break;
Example:
i = 0;
while 1:
print(i," ",end=""),
i=i+1;
if i == 10:
break;
print("came out of while loop");
Output:
continue Statement
The continue statement in python is used to bring the program control to the beginning of the
loop. The continue statement skips the remaining lines of code inside the loop and start with the
next iteration. It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition.
The syntax of Python continue statement is given below.
#loop statements
continue;
#the code to be skipped
Example :
i = 0;
while i!=10:
print("%d"%i);
continue;
i=i+1;
Output:
infinite loop
Example :
i=1
n=int(input("Enter the number up to which you want to print the natural numbers?"))
for i in range(0,10):
print(i,end = ' ')
Output:
0123456789
Example : printing the table of the given number
i=1;
num = int(input("Enter a number:"));
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i));
Output:
Enter a number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Nested for loop in python
Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n
number of times for every iteration of the outer loop. The syntax of the nested for loop in python
is given below.
for iterating_var1 in sequence:
for iterating_var2 in sequence:
#block of statements
#Other statements
Example :
n = int(input("Enter the number of rows you want to print?"))
i,j=0,0
for i in range(0,n):
print()
for j in range(0,i+1):
print("*",end="")
Output:
Enter the number of rows you want to print?5
*
**
***
****
*****
Using else statement with for loop
Unlike other languages like C, C++, or Java, python allows us to use the else statement with the
for loop which can be executed only when all the iterations are exhausted. Here, we must notice
that if the loop contains any of the break statement then the else statement will not be executed.
Example :
for i in range(0,5):
print(i)
else:print("for loop completely exhausted, since there is no break.");
In the above example, for loop is executed completely since there is no break statement in the
loop. The control comes out of the loop and hence the else block is executed.
Output:
0
1
2
3
4
for loop completely exhausted, since there is no break.
Exercise :
Very Short Answer Questions :
1. What is indentation ?
2. What is if statement ?
3. What is if else statement ?
4. Write the category of operator ?
5. What is looping ?
6. What is break statement ?
7. What is continue statement ?
1. What are various decision making statement. Explain them with examples.
2. Write the category of operators with example.
3. Write program for calculating the factorial of a number.
4. Write program to find sum of first n natural numbers.
Chapter 4
List, Tuples ,Sets & Dictionaries
LIST
A list is a standard data type of Python to store sequence of values belong to any type. List in
python is implemented to store the sequence of various type of data. However, python contains
six data types that are capable to store the sequences but the most common and reliable type is
list. A list can be defined as a collection of values or items of different types. The items in the list
are separated with the comma (,) and enclosed with the square brackets []. Lists are mutable i.e.
modifiable. In other words the memory address of list will not change even after you change its
values.
A list can be defined as follows.
1. L1 = ["Ram", 102, "Ambala"]
2. L2 = [1, 2, 3, 4, 5, 6]
3. L3 = [1, "Harshit"]
4. L4=[]
If we try to print the type of L1, L2, L3 and L4 then it will come out to be a list.
Lets consider a proper example to define a list and printing its values.
emp = ["Ram", 102, "Ambala"]
Dep1 = ["CS",10];
Dep2 = ["IT",11];
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT));
Output:
printing employee data...
Name : Ram, ID: 102, City: Ambala
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Harshit, Id: 100
IT HOD Name: Mr. Been, Id: 101
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>
List indexing and splitting
The indexing are processed in the same way as it happens with the strings. The elements of the
list can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th
index, the second element of the list is stored at the 1st index, and so on.
Consider the following example.
Unlike other languages, python provides us the flexibility to use the negative indexing also. The
negative indices are counted from the right. The last element (right most) of the list has the index
-1, its adjacent left element is present at the index -2 and so on until the left most element is
encountered.
Updating List values
Lists are the most versatile data structures in python since they are mutable and their values can
be updated by using the slice and assignment operator. Python also provide us the append()
method which can be used to add values to the string.
Consider the following example to update the values inside the list.
List = [1, 2, 3, 4, 5, 6]
print(List)
List[2] = 10;
print(List)
List[1:3] = [89, 78]
print(List)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
The list elements can also be deleted by using the del keyword. Python also provides us the
remove() method if we do not know which element is to be deleted from the list.
Consider the following example to delete the list elements.
List = [0,1,2,3,4]
print(List)
del List[0]
print(List)
del List[3]
print(List)
Output:
[0, 1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3]
Python List Operations
The concatenation (+) and repetition (*) operator work in the same way as they were working
with the strings.
Lets see how the list responds to various operators.
It returns true if a particular item exists in a particular list print(2 in l1) prints
Membership
otherwise false. True.
for i in l1:
print(i)
Output
Iteration The for loop is used to iterate over the list elements.
1
2
3
4
Length It is used to get the length of the list len(l1) = 4
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings can be iterated
as follows.
List = ["Ram", "Sham", "Mohan", "Sohan"]
for i in List: #i will iterate over the elements of the List and contains each element in each ite
ration.
print(i);
Output:
Ram
Sham
Mohan
Sohan
Adding elements to the list
Python provides append() function by using which we can add an element to the list. However,
the append() method can only add the value to the end of the list.
Consider the following example in which, we are taking the elements of the list from the user
and printing the list on the console.
l =[];
n = int(input("Enter the number of elements in the list")); #Number of elements will be enter
ed by the user
for i in range(0,n): # for loop to take the input
l.append(input("Enter the item?")); # The input is taken from the user and added to the list
as the item
print("printing the list items....");
for i in l: # traversal loop to print the list items
print(i, end = " ");
Output:
Enter the number of elements in the list 5
Enter the item?1
Enter the item?2
Enter the item?3
Enter the item?4
Enter the item?5
printing the list items....
1 2 3 4 5
Removing elements from the list
List = [0,1,2,3,4]
print("printing original list: ");
for i in List:
print(i,end=" ")
List.remove(0)
print("\nprinting the list after the removal of first element...")
for i in List:
print(i,end=" ")
Output:
printing original list:
01234
printing the list after the removal of first element...
1234
Python List Built-in functions
Python provides the following built-in functions which can be used with the lists.
SN Function Description
1 list.append(obj) The element represented by the object obj is added to the list.
4 list.count(obj) It returns the number of occurrences of the specified object in the list.
5 list.extend(seq) The sequence represented by the object seq is extended to the list.
6 list.index(obj) It returns the lowest index in the list that object appears.
7 list.insert(index, obj) The object is inserted into the list at the specified index.
11 list.sort([func]) It sorts the list by using the specified compare function if given.
Tuples
Python Tuple is used to store the sequence of immutable python objects. Tuple is similar to lists
since the value of the items stored in the list can be changed whereas the tuple is immutable and
the value of the items stored in the tuple can not be changed. A tuple can be written as the
collection of comma-separated values enclosed with the small brackets. A tuple can be defined
as follows.
1. T1 = (101, "Harry", 22)
2. T2 = ("Apple", "Banana", "Mango")
Example 1:
tuple1 = (10, 20, 30, 40, 50, 60)
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %d"%(count, i));
count=count+1
Output:
(10, 20, 30, 40, 50, 60)
tuple1[0] = 10
tuple1[1] = 20
tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60
Example 2:
tuple1 = tuple(input("Enter the tuple elements ..."))
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %s"%(count, i));
Output:
Enter the tuple elements ...12345
('1', '2', '3', '4', '5')
tuple1[0] = 1
tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
However, if we try to reassign the items of a tuple, we would get an error as the tuple object
doesn't support the item assignment.
An empty tuple can be written as follows.
T3 = ()
The tuple having a single value must include a comma as given below.
T4 = (90,)
A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using
their specific index value.
Tuple indexing and splitting
The indexing and slicing in tuple are similar to lists. The indexing in the tuple starts from 0 and
goes to length(tuple) - 1.
The items in the tuple can be accessed by using the slice operator. Python also allows us to use
the colon operator to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.
Unlike lists, the tuple items can not be deleted by using the del keyword as tuples are immutable.
To delete an entire tuple, we can use the del keyword with the tuple name.
Consider the following example.
tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
del tuple1[0]
print(tuple1)
del tuple1
print(tuple1)
Output:
(1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
File "tuple.py", line 4, in <module>
print(tuple1)
NameError: name 'tuple1' is not defined
Like lists, the tuple elements can be accessed in both the directions. The right most element (last)
of the tuple can be accessed by using the index -1. The elements from left to right are traversed
using the negative indexing.
Consider the following example.
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1])
print(tuple1[-4])
Output:
5
2
Basic Tuple operations
The operators like concatenation (+), repetition (*), Membership (in) works in the same way as
they work with the list. Consider the following table for more detail.
Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.
Operator Description Example
The repetition operator enables the tuple elements to be T1*2 = (1, 2, 3, 4, 5, 1,
Repetition
repeated multiple times. 2, 3, 4, 5)
It concatenates the tuple mentioned on either side of the T1+T2 = (1, 2, 3, 4, 5, 6,
Concatenation
operator. 7, 8, 9)
It returns true if a particular item exists in the tuple print (2 in T1) prints
Membership
otherwise false. True.
for i in T1:
print(i)
Output
Iteration The for loop is used to iterate over the tuple elements.
1
2
3
4
5
Length It is used to get the length of the tuple. len(T1) = 5
Python Tuple inbuilt functions
SN Function Description
cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than tuple2
1
tuple2) otherwise false.
2 len(tuple) It calculates the length of the tuple.
3 max(tuple) It returns the maximum element of the tuple.
4 min(tuple) It returns the minimum element of the tuple.
5 tuple(seq) It converts the specified sequence to the tuple.
List VS Tuple
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
2 The List is mutable. The tuple is immutable.
3 The List has the variable length. The tuple has the fixed length.
The list provides more functionality than
4 The tuple provides less functionality than the list.
tuple.
The list Is used in the scenario in which we The tuple is used in the cases where we need to
need to store the simple collections with store the read-only collections i.e., the value of
5
no constraints where the value of the items the items can not be changed. It can be used as
can be changed. the key inside the dictionary.
Sets
The set in python can be defined as the unordered collection of various items enclosed within the
curly braces. The elements of the set can not be duplicate. The elements of the python set must
be immutable. Unlike other collections in python, there is no index attached to the elements of
the set, i.e., we cannot directly access any element of the set by the index. However, we can print
them all together or we can get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma separated items with the curly braces. Python
also provides the set method which can be used to create the set by the passed sequence.
Example 1: using curly braces
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunda
y"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Example 2: using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Su
nday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Output:
{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}
<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday
Python Set operations
In the previous example, we have discussed about how the set is created in python. However, we
can perform various mathematical operations on python sets like union, intersection, difference,
etc.
Adding items to the set
Python provides the add() method which can be used to add some particular item to the set.
Consider the following example.
Example:
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
Output:
printing the original set ...
{'February', 'May', 'April', 'March', 'June', 'January'}
Adding other months to the set...
Printing the modified set...
{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}
looping through the set elements ...
February
July
May
April
March
August
June
January
Update method
To add more than one item in the set, Python provides the update() method.
Consider the following example.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);
Output:
printing the original set ...
{'January', 'February', 'April', 'May', 'June', 'March'}
updating the original set ...
printing the modified set ...
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}
Removing items from the set
Python provides discard() method which can be used to remove the items from the set.
Consider the following example.
Example
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.discard("January");
Months.discard("May");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
Output:
printing the original set ...
{'February', 'January', 'March', 'April', 'June', 'May'}
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'April', 'June'}
looping through the set elements ...
February
March
April
June
Remove method
Python also provide the remove() method to remove the items from the set. Consider the
following example to remove the items using remove() method.
Example
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.remove("January");
Months.remove("May");
print("\nPrinting the modified set...");
print(Months)
Output:
printing the original set ...
{'February', 'June', 'April', 'May', 'January', 'March'}
Removing some months from the set...
Printing the modified set...
{'February', 'June', 'April', 'March'}
Pop method
We can also use the pop() method to remove the item. However, this method will always remove
the last item. Consider the following example to remove the last item from the set.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.pop();
Months.pop();
print("\nPrinting the modified set...");
print(Months)
Output:
printing the original set ...
{'June', 'January', 'May', 'April', 'February', 'March'}
Removing some months from the set...
Printing the modified set...
{'May', 'April', 'February', 'March'}
Clear method
Python provides the clear() method to remove all the items from the set.
Consider the following example.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving all the items from the set...");
Months.clear()
print("\nPrinting the modified set...")
print(Months)
Output:
printing the original set ...
{'January', 'May', 'June', 'April', 'March', 'February'}
Removing all the items from the set...
Printing the modified set...
Dictionaries
Dictionary is used to implement the key-value pair in python. The dictionary is the data type in
python which can simulate the real-life data arrangement where some specific value exists for
some particular key. In other words, we can say that a dictionary is the collection of key-value
pairs where the value can be any python object whereas the keys are the immutable python
object, i.e., Numbers, string or tuple.
Creating the dictionary
The dictionary can be created by using multiple key-value pairs enclosed with the small brackets
() and separated by the colon (:). The collections of the key-value pairs are enclosed within the
curly braces {}.
The syntax to define the dictionary is given below.
Dict = {"Name": "Ayush","Age": 22}
In the above dictionary Dict, The keys Name, and Age are the string that is an immutable object.
Let's see an example to create a dictionary and printing its content.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Age': 29, 'salary': 25000, 'Name': 'John', 'Company': 'GOOGLE'}
Accessing the dictionary values
We have discussed how the data can be accessed in the list and tuple by using the indexing.
However, the values can be accessed in the dictionary by using the keys as keys are unique in the
dictionary.
The dictionary values can be accessed in the following way.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
Python provides us with an alternative to use the get() method to access the dictionary values. It
would give the same result as given by the indexing.
Updating dictionary values
The dictionary is a mutable data type, and its values can be updated by using the specific keys.
Let's see an example to update the dictionary values.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
Output:
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'salary': 25000, 'Company': 'GOOGLE', 'Age': 29}
Enter the details of the new employee....
Name: David
Age: 19
Salary: 8900
Company:JTP
printing the new data
{'Name': 'David', 'salary': 8900, 'Company': 'JTP', 'Age': 19}
Iterating Dictionary
A dictionary can be iterated using the for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(x);
Output:
Name
Company
salary
Age
Example 2
#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(Employee[x]);
Output:
29
GOOGLE
John
25000
Sorting Dictionaries
color_dict = {'Name':'Ram',
'Pay':'8000',
'Dept':'Sale',
'Gender':'Male'}
Dept: Sale
Gender: Male
Name: Ram
Pay: 8000
Copying Collections
Exercise :
Very Short Answer type questions :
1. Explain tuple.
2. What is list ?
3. What is set ?
4. What is dictionary?
5. What is union?
6. What is intersection?
7. What is push operation?
8. What is pop operation?
Function calling
In python, a function must be defined before the function calling otherwise the python interpreter
gives an error. Once the function is defined, we can call it from another function or the python
prompt. To call the function, use the function name followed by the parentheses.
A simple function that prints the message "Hello Word" is given below.
def hello_world():
print("hello world")
hello_world()
Output:
hello world
Parameters in function
The information into the functions can be passed as the parameters. The parameters are specified
in the parentheses. We can give any number of parameters, but we have to separate them with a
comma. Consider the following example which contains a function that accepts a string as the
parameter and prints it.
Example 1
#defining the function
def func (name):
print("Hi ",name);
#calling the function
func("Ashu")
Output :
Hi Ashu
Example 2
#python function to calculate the sum of two variables
#defining the function
def sum (a,b):
return a+b;
#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
#printing the sum of a and b
print("Sum = ",sum(a,b))
Output:
Enter a: 10
Enter b: 20
Sum = 30
Call by reference in Python/Passing Collections to Functions
In python, all the functions are called by reference, i.e., all the changes made to the reference
inside the function revert back to the original value referred by the reference. However, there is
an exception in the case of mutable objects since the changes made to the mutable objects like
string do not revert to the original string rather, a new string object is made, and therefore the
two different objects are printed.
Example 1 Passing Immutable Object (List)
#defining the function
def change_list(list1):
list1.append(20);
list1.append(30);
print("list inside function = ",list1)
#defining the list
list1 = [10,30,40,50]
#calling the function
change_list(list1);
print("list outside function = ",list1);
Output:
list inside function = [10, 30, 40, 50, 20, 30]
list outside function = [10, 30, 40, 50, 20, 30]
Example 2 Passing Mutable Object (String)
#defining the function
def change_string (str):
str = str + " Hello";
print("printing the string inside function :",str);
string1 = "Hi I am there"
#calling the function
change_string(string1)
print("printing the string outside function :",string1)
Output:
printing the string inside function : Hi I am there Hows you
printing the string outside function : Hi I am there
Types of arguments
There may be several types of arguments which can be passed at the time of function calling.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required Arguments
Till now, we have learned about function calling in python. However, we can provide the
arguments at the time of function calling. As far as the required arguments are concerned, these
are the arguments which are required to be passed at the time of function calling with the exact
match of their positions in the function call and function definition. If either of the arguments is
not provided in the function call, or the position of the arguments is changed, then the python
interpreter will show the error.
Consider the following example.
Example 1
#the argument name is the required argument to the function func
def func(name):
message = "Hi "+name;
return message;
name = input("Enter the name?")
print(func(name))
Output:
Enter the name?Ravi
Hi Ravi
Example 2
#the function simple_interest accepts three arguments and returns the simple interest accordingly
def simple_interest(p,t,r):
return (p*t*r)/100
p = float(input("Enter the principle amount? "))
r = float(input("Enter the rate of interest? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,r,t))
Output:
Enter the principle amount? 10000
Enter the rate of interest? 5
Enter the time in years? 2
Simple Interest: 1000.0
2. Keyword arguments
Python allows us to call the function with the keyword arguments. This kind of function call will
enable us to pass the arguments in the random order. The name of the arguments is treated as the
keywords and matched in the function calling and definition. If the same match is found, the
values of the arguments are copied in the function definition.
Example 1
#function func is called with the name and message as the keyword arguments
def func(name,message):
print("printing the message with",name,"and ",message)
func(name = "Ravi",message="hello") #name and message is copied with the values John and he
llo respectively
Output:
printing the message with Ravi and hello
Example 2 providing the values in different order at the calling
#The function simple_interest(p, t, r) is called with the keyword arguments the order of argument
s doesn't matter in this case
def simple_interest(p,t,r):
return (p*t*r)/100
print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))
Output:
Simple Interest: 1900.0
3. Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of the
argument is not provided at the time of function call, then that argument can be initialized with
the value given in the definition even if the argument is not specified at the function call.
Example 1
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john") #the variable age is not passed into the function however the default val
ue of age is considered in the function
Output:
My name is john and age is 22
4. Variable length Arguments
In the large projects, sometimes we may not know the number of arguments to be passed in
advance. In such cases, Python provides us the flexibility to provide the comma separated values
which are internally treated as tuples at the function call. However, at the function definition, we
have to define the variable with * (star) as *<variable - name >.
Example
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("Rohan","Sohan","Mohan","Nikhil")
Output:
type of passed argument is <class 'tuple'>
printing the passed arguments...
Rohan
Sohan
Mohan
Nikhil
Scope of variables
The scopes of the variables depend upon the location where the variable is being declared. The
variable declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global scope whereas the variable
defined inside a function is known to have a local scope.
Example 1
def print_message():
message = "hello !! I am going to print a message." # the variable message is local to the funct
ion itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be accessible here.
Output:
hello !! I am going to print a message.
File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in
print(message)
NameError: name 'message' is not defined
Example 2
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed
Output:
The sum is 60
Value of sum outside the function: 0
First class objects in a language are handled uniformly throughout. They may be stored in data
structures, passed as arguments, or used in control structures. A programming language is said to
support first-class functions if it treats functions as first-class objects. Python supports the
concept of First Class functions.
Properties of first class functions:
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists, …
Functions are objects: Python functions are first class objects. In the example below, we are
assigning function to a variable.
def whisper(text):
return text.lower()
def greet(func):
# storing the function in a variable
greeting = func("Hi, I am created by a function passed as an argument.")
print greeting
greet(shout)
greet(whisper)
Output
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
Map
map() function returns a list of the results after applying the given function to each item of a
given iterable (list, tuple etc.)
Syntax :
map(fun, iter)
Parameters :
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.
NOTE : You can pass one or more iterable to the map() function.
# Python program to demonstrate working
# of map.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
filter
element in the sequence to be true or not.
syntax:
filter(function, sequence)
Parameters:
function: function that tests if each element of a
sequence true or not.
sequence: sequence which needs to be filtered, it can
be sets, lists, tuples, or containers of any iterators.
Retruns:
returns an iterator that is already filtered.
# function that filters vowels
def fun(variable):
letters = ['a', 'e', 'i', 'o', 'u']
if (variable in letters):
return True
else:
return False
# sequence
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']
# using filter function
filtered = filter(fun, sequence)
print('The filtered letters are:')
for s in filtered:
print(s)
released = {
"iphone" : 2007,
print released
Lambda
A lambda function is a small anonymous function. A lambda function can take any number of
arguments, but can only have one expression
Syntax
Example
A lambda function that adds 10 to the number passed in as an argument, and print the result:
x = lambda a : a + 10
print(x(5))
Example
A lambda function that multiplies argument a with argument b and print the result:
x = lambda a, b : a * b
print(x(5, 6))
Inner Functions
To define an inner function in Python, we simply create a function inside another function using
the Python's def keyword. Here is an example:
Closures
Closure is basically keeping a record of a function with an environment. For example, if we call
a function with an argument (foo(1)), then it must keep a record of the environment with that
argument to be used later in the program. It will be clear from the examples given below.
def f1(a):
def f2(b):
return a+b
return f2
a = f1(1)
b = f1(100)
print (a(2))
print (b(2))
Output
102
You can see that the environment created by f1(1) is different from that of f1(100), and both
were remembered by Python, thus printing different values for a(2) and b(2). This is what
closure is.
So basically, a function (object) that remembers the environment where it was made is a closure.
A closure is also the answer to the question - "What is the use of nested function". But this also
gives us another question - "What is the use of closures?"
Classes are more flexible than closures but closures are faster. One can make closures to handle
simple cases where making a class is not really necessary.
Chapter 6
Modules
A python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our python code
file saved with the extension (.py) is treated as the module. We may have a runnable code inside
the python module. Modules in Python provides us the flexibility to organize the code in a
logical way.
To use the functionality of one module into another, we must have to import the specific module.
Example
In this example, we will create a module named as file.py which contains a function func that
contains a code to print some message on the console.
Let's create the module named as file.py.
#displayMsg prints a message to the name being passed.
def displayMsg(name)
print("Hi "+name);
Here, we need to include this module into our main module to call the method displayMsg()
defined in the module named file.
Loading the module in our python code
We need to load the module in our python code to use its functionality. Python provides two
types of statements as defined below.
1. The import statement
2. The from-import statement
The import statement
The import statement is used to import all the functionality of one module into another. Here, we
must notice that we can use the functionality of any python source file by importing that file as
the module into another python source file.
We can import multiple modules with a single import statement, but a module is loaded once
regardless of the number of times, it has been imported into our file.
The syntax to use the import statement is given below.
import module1,module2,........ module n
Hence, if we need to call the function displayMsg() defined in the file file.py, we have to import
that file as a module into our module as shown in the example below.
Example:
import file;
name = input("Enter the name?")
file.displayMsg(name)
Output:
Enter the name?Kavi
Hi Kavi
The from-import statement
Instead of importing the whole module into the namespace, python provides the flexibility to
import only the specific attributes of a module. This can be done by using from? import
statement. The syntax to use the from-import statement is given below.
from < module-name> import <name 1>, <name 2>..,<name n>
Consider the following module named as calculation which contains three functions as
summation, multiplication, and divide.
calculation.py:
#place the code in the calculation.py
def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;
Main.py:
from calculation import summation
#it will import only the summation() from calculation.py
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing su
mmation()
Output:
Enter the first number10
Enter the second number20
Sum = 30
The from...import statement is always better to use if we know the attributes to be imported from
the module in advance. It doesn't let our code to be heavier. We can also import all the attributes
from a module by using *.
Consider the following syntax.
from <module> import *
Renaming a module
Python provides us the flexibility to import some module with a specific name so that we can use
this name to use that module in our python source file.
The syntax to rename a module is given below.
import <module-name> as <specific-name>
Example
#the module calculation of previous example is imported in this example as cal.
import calculation as cal;
a = int(input("Enter a?"));
b = int(input("Enter b?"));
print("Sum = ",cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
sys.maxsize
Returns the largest integer a variable can take.
>>> import sys
>>>sys.maxsize
9223372036854775807
sys.path
This is an environment variable that is a search path for all Python modules.
>>>sys.path
['', 'C:\\python36\\Lib\\idlelib', 'C:\\python36\\python36.zip', 'C:\\python36\\DLLs',
'C:\\python36\\lib', 'C:\\python36', 'C:\\Users\\acer\\AppData\\Roaming\\Python\\Python36\\site-
packages', 'C:\\python36\\lib\\site-packages']
sys.version
This attribute displays a string containing the version number of the current Python interpreter.
>>>sys.version
'3.7.0 (v3.7.0:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)]'
Pie (π) is a well-known mathematical constant, which is defined as the ratio of the circumference
to the diameter of a circle and its value is 3.141592653589793.
>>> import math
>>>math.pi
3.141592653589793
Another well-known mathematical constant defined in the math module is e. It is called Euler's
number and it is a base of the natural logarithm. Its value is 2.718281828459045.
>>>math.e
2.718281828459045
The math module contains functions for calculating various trigonometric ratios for a given
angle. The functions (sin, cos, tan, etc.) need the angle in radians as an argument. We, on the
other hand, are used to express the angle in degrees. The math module presents two angle
conversion functions: degrees() and radians(), to convert the angle from degrees to radians and
vice versa. For example, the following statements convert the angle of 30 degrees to radians and
back (Note: π radians is equivalent to 180 degrees).
>>>math.radians(30)
0.5235987755982988
>>>math.degrees(math.pi/6)
29.999999999999996
The following statements show sin, cos and tan ratios for the angle of 30 degrees
(0.5235987755982988 radians):
>>math.sin(0.5235987755982988)
0.49999999999999994
>>>math.cos(0.5235987755982988)
0.8660254037844387
>>>math.tan(0.5235987755982988)
0.5773502691896257
You may recall that sin(30)=0.5, cos(30)=32 (which is 0.8660254037844387) and tan(30)= 13
(which is 0.5773502691896257).
math.log()
The math.log() method returns the natural logarithm of a given number. The natural logarithm is
calculated to the base e.
>>>math.log(10)
2.302585092994046
math.log10()
The math.log10() method returns the base-10 logarithm of the given number. It is called the
standard logarithm.
>>>math.log10(10)
1.0
math.exp()
The math.exp() method returns a float number after raising e (math.e) to given number. In other
words, exp(x) gives e**x.
>>>math.log10(10)
1.0
This can be verified by the exponent operator.
>>>math.e**10
22026.465794806703
math.pow()
The math.pow() method receives two float arguments, raises the first to the second and returns
the result. In other words, pow(4,4) is equivalent to 4**4.
>>>math.pow(2,4)
16.0
>>>2**4
16
math.sqrt()
The math.sqrt() method returns the square root of a given number.
>>>math.sqrt(100)
10.0
>>>math.sqrt(3)
1.7320508075688772
The following two functions are called representation functions. The ceil() function
approximates the given number to the smallest integer, greater than or equal to the given floating
point number. The floor() function returns the largest integer less than or equal to the given
number.
>>>math.ceil(4.5867)
5
>>>math.floor(4.5687)
4
Standard Modules - time
In the real world applications, there are the scenarios where we need to work with the date and
time. There are the examples in python where we have to schedule the script to run at some
particular timings.
In python, the date is not a data type, but we can work with the date objects by importing the
module named with datetime, time, and calendar.
Tick
In python, the time instants are counted since 12 AM, 1st January 1970. The function time() of
the module time returns the total number of ticks spent since 12 AM, 1st January 1970. A tick
can be seen as the smallest unit to measure the time.
Consider the following example.
Example
import time;
#prints the number of ticks spent since 12 AM, 1st January 1970
print(time.time())
Output:
1545124460.9151757
The localtime() functions of the time module are used to get the current time tuple. Consider the
following example.
Example
import time;
#returns a time tuple
print(time.localtime(time.time()))
Output:
time.struct_time(tm_year=2018, tm_mon=12, tm_mday=18, tm_hour=15, tm_min=1,
tm_sec=32, tm_wday=1, tm_yday=352, tm_isdst=0)
Time tuple
The time is treated as the tuple of 9 numbers. Let's look at the members of the time tuple.
Index Attribute Values
0 Year 4 digit (for example 2018)
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 60
6 Day of weak 0 to 6
7 Day of year 1 to 366
8 Daylight -1, 0, 1 , or -1
savings
December 2018
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Example
import json
List = dir(json)
print(List)
Output:
['JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__', '__cached__',
'__doc__',
'__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__',
'_default_decoder', '_default_encoder', 'decoder', 'dump', 'dumps', 'encoder', 'load',
'loads', 'scanner']
Exercise :
Very Short Answer Type Questions :
1. What is module ?
2. What is the extension of module file ?
3. What is import statement ?
4. Write the Names of modules.
5. What is dir ?
1. What is module ? How it is created and used in Python? What is its role ?
2. Explain various built in modules in Python with example.
Chapter 7.
Exceptions
An exception can be defined as an abnormal condition in a program resulting in the disruption in
the flow of the program. Whenever an exception occurs, the program halts the execution, and
thus the further code is not executed. Therefore, an exception is the error which python script is
unable to tackle with.
Python provides us with the way to handle the Exception so that the other part of the code can be
executed without any disruption. However, if we do not handle the exception, the interpreter
doesn't execute all the code that exists after that.
Common Exceptions
A list of common exceptions that can be thrown from a normal python program is given below.
1. ZeroDivisionError: Occurs when a number is divided by zero.
2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
Problem without handling exceptions
As we have already discussed, the exception is an abnormal condition that halts the execution of
the program. Consider the following example.
Example
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
#other code:
print("Hi I am other part of the program")
Output:
Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
If the python program contains suspicious code that may throw the exception, we must place that
code in the try block. The try block must be followed with the except statement which contains a
block of code that will be executed if there is some exception in the try block.
Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
We can also use the else statement with the try-except statement in which, we can place the code
which will be executed in the scenario if no exception occurs in the try block.
The syntax to use the else statement with the try-except statement is given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
else:
print("Hi I am else block")
Output:
Enter a:10
Enter b:2
a/b = 5
Hi I am else block
The except statement with no exception
Python provides the flexibility not to specify the name of exception with the except statement.
Consider the following example.
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
Output:
Enter a:10
Enter b:0
can't divide by zero
Points to remember
1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.
3. We can also specify an else block along with the try-except statement which will be
executed if no exception is raised in the try block.
4. The statements that don't throw the exception should be placed inside the else block.
Example
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
Output:
File not found
Declaring multiple exceptions
The python allows us to declare the multiple exceptions with the except clause. Declaring
multiple exceptions is useful in the cases where a try block throws multiple exceptions.
Syntax
try:
#block of code
except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)
#block of code
else:
#block of code
Example
try:
a=10/0;
except ArithmeticError,StandardError:
print "Arithmetic Exception"
else:
print "Successfully Done"
Output:
Arithmetic Exception
The finally block
We can use the finally block with the try block in which, we can pace the important code which
must be executed before the try statement throws an exception.
The syntax to use the finally block is given below.
syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
Example
try:
fileptr = open("file.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
Output:
file closed
Error
Raising exceptions
An exception can be raised by using the raise clause in python. The syntax to use the raise
statement is given below.
syntax
raise Exception_class,<value>
Points to remember
1. To raise an exception, raise statement is used. The exception class name follows it.
2. An exception can be provided with a value that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable which stores
the value of the exception.
Example
try:
age = int(input("Enter the age?"))
if age<18:
raise ValueError;
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Output:
Enter the age?17
The age is not valid
Example
try:
a = int(input("Enter a?"))
b = int(input("Enter b?"))
if b is 0:
raise ArithmeticError;
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")
Output:
Enter a?10
Enter b?0
The value of b can't be 0
Custom Exception
The python allows us to create our exceptions that can be raised from the program and caught
using the except clause. However, we suggest you read this section after visiting the Python
object and classes.
Consider the following example.
Example
class ErrorInCode(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)
try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", ae.data)
Output:
Received error: 2000
Python - Assert Statement
Python provides the assert statement to check if a given logical expression is true or false.
Program execution proceeds only if the expression is true and raises the AssertionError when it
is false. The following code shows the usage of the assert statement.
Example: assert
num=int(input('Enter a number: '))
assert num>=0
print('You entered: ', num)
The print statement will display if the entered number is greater than or equal to 0. Negative
numbers result in aborting the program after showing the AssertionError.
Result:
Enter a number: 100
You entered 100
Enter a number: -10
Traceback (most recent call last):
File "C:/python36/xyz.py", line 2, in <module>
assert num>=0
AssertionError
The assert statement can optionally include an error message string, which gets displayed along
with the AssertionError. In the above code, you can change the assert statement to the following
and run the code:
Example: assert
num=int(input('Enter a number: '))
assert num>=0, "Only positive numbers accepted."
print('You entered: ', num)
Output:
Enter a number: -10
Traceback (most recent call last):
File "C:/python36/xyz.py", line 2, in <module>
assert num>=0, "Only positive numbers accepted."
AssertionError: Only positive numbers accepted.
The AssertionError is also a built-in exception and can be handled using the try...except
construct as follows:
Example: AssertionError
try:
num=int(input('Enter a number: '))
assert(num >=0), "Only positive numbers accepted."
print(num)
except AssertionError as msg:
print(msg)
When the input causes an AssertionError, the program will not terminate, as was the case earlier.
Instead, it will be handled by the except block. The error message in the assert statement will be
passed as argument to the exception argument msg, using keyword as.
Output:
Enter a number: -10
Only positive numbers accepted.
Exercise :
Very Short Answer Questions :
1. What is exception ?
2. Write some name of exception?
3. What is try statement ?
4. What is catch statement ?
5. What is finally statement ?
6. Explain assert statement.
It opens the file to write only. It overwrites the file if previously exists or creates a new one
5 w
if no file exists with the same name. The file pointer exists at the beginning of the file.
It opens the file to write only in binary format. It overwrites the file if it exists previously or
6 wb
creates a new one if no file exists with the same name. The file pointer exists at the
beginning of the file.
It opens the file to write and read both. It is different from r+ in the sense that it overwrites
7 w+ the previous file if one exists whereas r+ doesn?t overwrite the previously written file. It
creates a new file if no file exists. The file pointer exists at the beginning of the file.
It opens the file to write and read both in binary format. The file pointer exists at the
8 wb+
beginning of the file.
It opens the file in the append mode. The file pointer exists at the end of the previously
9 a
written file if exists any. It creates a new file if no file exists with the same name.
It opens the file in the append mode in binary format. The pointer exists at the end of the
10 ab previously written file. It creates a new file in binary format if no file exists with the same
name.
It opens a file to append and read both. The file pointer remains at the end of the file if a file
11 a+
exists. It creates a new file if no file exists with the same name.
It opens a file to append and read both in binary format. The file pointer remains at the end
12 ab+
of the file.
Let's look at the simple example to open a file named "file.txt" (stored in the same directory) in read mode
and printing its content on the console.
Example
#opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
Output:
<class '_io.TextIOWrapper'>
file is opened successfully
Exercise :
Very Short Answer Question
Object
Class
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation
Object
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the doc string defined in the function
source code.
Class
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class then it should contain an
attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
Method
The method is a function that is associated with an object. In Python, a method is not unique to
class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming which simulates the real
world concept of inheritance. It specifies that the child object acquires all the properties and
behaviors of the parent object. By using inheritance, we can create a class which uses all the
properties and behavior of another class. The new class is known as a derived class or child
class, and the one whose properties are acquired is known as a base class or parent class. It
provides re-usability of the code.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many and Morphs means
form, shape. By polymorphism, we understand that one task can be performed in different ways.
For example You have a class animal, and all animals speak. But they speak differently. Here,
the "speak" behavior is polymorphic in the sense and depends on the animal. So, the abstract
"animal" concept does not actually "speak", but specific animals (like dogs and cats) have a
concrete implementation of the action "speak".
Encapsulation
Encapsulation is also an important aspect of object-oriented programming. It is used to restrict
access to methods and variables. In encapsulation, code and data are wrapped together within a
single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonym
because data abstraction is achieved through encapsulation. Abstraction is used to hide internal
details and show only functionalities. Abstracting something means to give names to things so
that the name captures the core of what a function or a whole program does.
Object-oriented vs Procedure-oriented Programming languages
Index Object-oriented Programming Procedural Programming
It simulates the real world entity. So real- It doesn't simulate the real world. It works
3. world problems can be easily solved through on step by step instructions divided into
oops. small parts called functions.
It provides data hiding. So it is more secure Procedural language doesn't provide any
4. than procedural languages. You cannot access proper way for data binding, so it is less
private data from anywhere. secure.
As we have already discussed, a class is a virtual entity and can be seen as a blueprint of an
object. The class came into existence when it instantiated. Let's understand it by an example.
Suppose a class is a prototype of a building. A building contains all the details about the floor,
doors, windows, etc. we can make as many buildings as we want, based on these details. Hence,
the building can be seen as a class, and we can create as many objects of this class. On the other
hand, the object is the instance of a class. The process of creating an object can be called as
instantiation.
Creating classes in python
In python, a class can be created by using the keyword class followed by the class name. The
syntax to create a class is given below.
Syntax
class ClassName:
#statement_suite
In python, we must notice that each class is associated with a documentation string which can be
accessed by using <class-name>.__doc__. A class contains a statement suite including fields,
constructor, function, etc. definition.
Consider the following example to create a class Employee which contains two fields as
Employee id, and name.
The class also contains a function display() which is used to display the information of the
Employee.
Example
class Employee:
id = 10;
name = "ayush"
def display (self):
print(self.id,self.name)
Here, the self is used as a reference variable which refers to the current class object. It is always
the first argument in the function definition. However, using self is optional in the function call.
<object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined in the above example.
Example
class Employee:
id = 10;
name = "Ravi"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
emp = Employee()
emp.display()
Output:
ID: 10
Name: Ravi
Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.
Constructors can be of two types.
Parameterized Constructor
Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough resources for the object to perform any start-up task.
Creating the constructor in python
In python, the method __init__ simulates the constructor of the class. This method is called when
the class is instantiated. We can pass any number of arguments at the time of creating the class
object, depending upon __init__ definition. It is mostly used to initialize the class attributes.
Every class must have a constructor, even if it simply relies on the default constructor.
Consider the following example to initialize the Employee class attributes.
Example
class Employee:
def __init__(self,name,id):
self.id = id;
self.name = name;
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
emp1 = Employee("Ravi",101)
emp2 = Employee("Harshit",102)
#accessing display() method to print employee 1 information
emp1.display();
#accessing display() method to print employee 2 information
emp2.display();
Output:
ID: 101
Name: Ravi
ID: 102
Name: Harshit
Output:
The number of students: 3
Output:
This is non parametrized constructor
Hello Ravi
Output:
This is parametrized constructor
Hello Ravi
print(hasattr(s,'id'))
# deletes the attribute age
delattr(s,'age')
# this will give an error since the attribute age has been deleted
print(s.age)
Output:
Ravi
23
True
AttributeError: 'Student' object has no attribute 'age'
Built-in class attributes
Along with the other attributes, a python class also contains some built-in class attributes which
provide information about the class.
The built-in class attributes are given in the below table.
SN Attribute Description
1 __dict__ It provides the dictionary containing the information about the
class namespace.
2 __doc__ It contains a string which has the class documentation
3 __name__ It is used to access the class name.
4 __module__ It is used to access the module in which, this class is
defined.
5 __bases__ It contains a tuple including all base classes.
Example
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
s = Student("Ravi",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Output:
None
{'name': 'Ravi’', 'id': 101, 'age': 22}
__main__
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code
reusability to the program because we can use an existing class to create a new class instead of
creating it from scratch. In inheritance, the child class acquires the properties and can access all
the data members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class. In python, a derived class can
inherit base class by just mentioning the base in the bracket after the derived class name.
Consider the following syntax to inherit a base class into the derived class.
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output:
30
200
0.5
Output:
True
False
Output:
True
Method Overriding
We can provide some specific implementation of the parent class method in our child class.
When the parent class method is defined in the child class with some specific implementation,
then the concept is called method overriding. We may need to perform method overriding in the
scenario where the different definition of a parent class method is needed in the child class.
Consider the following example to perform method overriding in python.
Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Output:
Barking
Output:
The number of employees 2
AttributeError: 'Employee' object has no attribute '__count'
Exercise :
Very Short Answer Questions :
1. What is OOPS ?
2. Explain class.
3. Explain object.
4. What is Polymorphism ?
5. What is inheritance ?
6. What is constructor ?
For instance, a regular expression could tell a program to search for specific text from the string
and then to print out the result accordingly. Expression can include Text matching, Repetition,
Branching & Pattern-composition etc.
In Python, a regular expression is denoted as RE (REs, regexes or regex pattern) are imported
through re module. Python supports regular expression through libraries. In Python regular
expression supports various things like Modifiers, Identifiers, and White space characters.
SN Function Description
This method matches the regex pattern in the string with the optional flag. It returns true if
1 match
a match is found in the string otherwise it returns false.
2 search This method returns the match object if there is a match found in the string.
3 findall It returns a list that contains all the matches of a pattern in the string.
4 split Returns a list in which the string has been split in each match.
Example :
import re
str = "How are you. How is everything"
matches = re.findall("How", str)
print(matches)
Output:
['How', 'How']
Special Characters
Metacharacter/Special character is a character with the specified meaning.
Example
import re
str = "The Computer Programming"
#Find all lower case characters alphabetically between "a" and "m":
x = re.findall("[a-m]", str)
print(x)
Output:
['h', 'e', 'm', 'e', 'g', 'a', 'm', 'm', 'i', 'g']
import re
str = "hello world"
#Check if the string starts with 'hello':
x = re.findall("^hello", str)
if (x):
print("Yes, the string starts with 'hello'")
else:
print("No match")
Output :
Yes, the string starts with 'hello'
Character Classes
A special sequence is a \ followed by one of the characters in the list below, and has a special
meaning:
Example :
import re
str = "The Computer Programming"
#Check if the string starts with "The":
x = re.findall("\AThe", str)
print(x)
if (x):
print("Yes, there is a match!")
else:
print("No match")
Output :
['The']
Yes, there is a match!
Quantifiers
A quantifier after a token, which can be a single character or group in brackets, specifies how
often that preceding element is allowed to occur. The most common quantifiers are
import re
str = "The Computer Programming requires logic skills"
#Check if the string contains "pu" followed by 0 or more "c" characters:
x = re.findall("puc*", str)
print(x)
if (x):
print("Yes, there is at least one match!")
else:
print("No match")
Output :
['pu']
Yes, there is at least one match!
The Dot Character
Dot character represents any character (except newline character)in expression.
import re
str = "hello world"
#Search for a sequence that starts with "he", followed by two (any) characters, and an "o":
x = re.findall("he..o", str)
print(x)
Output :
['hello']
Greedy Matches
The '*', '+', and '?' quantifiers are all greedy; they match as much text as possible. Adding ? after
the quantifier makes it perform the match in non-greedy or minimal fashion; as few characters as
possible will be matched.
Example :
import re
string = "<h1>Heading</h1><p>HTML text.</p>"
match = re.search("<.*>", string)
if match:
print("Greedy")
print("start:", match.start(0))
print("end:", match.end(0))
print("group:", match.group(0))
match = re.search("<.*?>", string)
if match:
print("\nNon-greedy")
print("start:", match.start(0))
print("end:", match.end(0))
print("group:", match.group(0))
Output:
Greedy
start: 0
end: 33
group: <h1>Heading</h1><p>HTML text.</p>
Non-greedy
start: 0
end: 4
group: <h1>
Grouping
Match groups match whatever regular expression is inside parentheses, and indicates the start
and end of a group; the contents of a group can be retrieved after a match has been performed.
Example:
import re
string = "<p>HTML text.</p>"
match = re.match("<p>(.*)</p>", string)
if match:
print("start:", match.start(1))
print("end:", match.end(1))
print("group:", match.group(1))
string = "'cat': 'Frisky', 'dog': 'Spot', 'fish': 'Bubbles'"
match = re.search("'cat': '(.*?)', 'dog': '(.*?)', 'fish': '(.*?)'", string)
if match:
print("groups:", match.group(1), match.group(2), match.group(3))
Output:
start: 3
end: 13
group: HTML text.
groups: Frisky Spot Bubbles
Matching at Beginning or End
^ searches string in the given expression from the beginning
import re
str = "hello world"
#Check if the string starts with 'hello':
x = re.findall("^hello", str)
if (x):
print("Yes, the string starts with 'hello'")
else:
print("No match")
Output :
Yes, the string starts with 'hello'
$ searches string in the given expression at the end.
import re
str = "hello world"
#Check if the string ends with 'world':
x = re.findall("world$", str)
if (x):
print("Yes, the string ends with 'world'")
else:
print("No match")
Output :
Yes, the string ends with 'hello'
Match Objects
The match object contains the information about the search and the output. If there is no match
found, the None object is returned.
Example
import re
str = "How are you. How many lines ?"
matches = re.search("How", str)
print(type(matches))
print(matches) #matches is the search object
Output:
<class '_sre.SRE_Match'>
<_sre.SRE_Match object; span=(0, 3), match='How'>
Output:
(0, 3)
How
How are you. How is everything
Substituting
Substituting means replacing one character/string with another. The sub() function replaces the
matches with the text of your choice.
Example :
import re
#Replace all white-space characters with the digit "9":
str = "The rain in Spain"
x = re.sub("\s", "9", str)
print(x)
Splitting a String
The split() function returns a list where the string has been split at each match.
Example :
import re
#Split the string at every white-space character:
str = "The rain in Spain"
x = re.split("\s", str)
print(x)
Compilation flags let you modify some aspects of how regular expressions work. Flags are
available in the re module under two names, a long name such as IGNORECASE and a short,
one-letter form such as I.
Example:
import re
xx = """guru99
careerguru99
selenium"""
k1 = re.findall(r"^\w", xx)
k2 = re.findall(r"^\w", xx, re.MULTILINE)
print(k1)
print(k2)
Exercise:
Very Short Answer Questions :
1. What is regular expression ?
2. What is match function
3. What is quantifiers ?
4. What is the function of dot character ?
5. What characters are used for searching in beginning and at end ?
6. What is flag ?
Short Answer Questions :
1. What are special characters used in regular expression ?
2. Explain character classes used in regular expression.
3. Expalin different quantifiers.
4. What is greedy match ?
5. Explain Grouping in regular expression.
6. How can you match objects ?
7. What is Substituting ?
8. What is splitting ?
lower
count
replace
Answer : a) Lower function
output :
hello, world!
b) count function
count method returns an integer that denotes number of times a substring occurs in a given
string.
a = "Hello, World! Hello, Python"
print(a.count("Hello"))
output :
2
c) replace function
a = "Hello, World!"
print(a.replace("H", "J"))
Output:
Jello, World!
2. Write instructions to perform each of the steps below
(a) Create a string containing at least five words and store it in a variable.
(b) Print out the string.
(c) Convert the string to a list of words using the string split method.
(d) Sort the list into reverse alphabetical order using some of the list methods
(e) Print out the sorted, reversed list of words.
Answer :
#creating string to store five words
a = "Apple,Ornage,Banana,Mango,Grapes"
#printing string
print(a)
#splitting the string
b = a.split(",")
#printing splitted string
print(b)
#sorting the list in reverse order
b.sort(reverse=True)
#printing the reverse list
print (b)
Output :
Apple,Ornage,Banana,Mango,Grapes
['Apple', 'Ornage', 'Banana', 'Mango', 'Grapes']
['Ornage', 'Mango', 'Grapes', 'Banana', 'Apple']
3. Write a program that determines whether the number is prime.
Answer :
#to check whether a number is prime no. or not prime no
n=int(input("Enter a number "))
r=2
while (r<n):
if(n%r)==0:
print(n," is not a prime no")
break;
r=r+1
if(n==r):
print(n, " is a prime no")
Output :
Enter a number 8
8 is not a prime no
Enter a number 7
7 is a prime no
4. Find all numbers which are multiple of 17, but not the multiple of 5, between 2000
and 2500?
#numbers which are multiple of 17, but not the multiple of 5, between 2000 and 2500
print(“numbers multiple of 17, but not the multiple of 5, between 2000 and 2500 “)
for i in range(2000,2501):
if (i % 17==0) and(not(i % 5==0)):
print (i)
Output :
numbers multiple of 17, but not the multiple of 5, between 2000 and 2500
2006
2023
2057
2074
2091
2108
2142
2159
2176
2193
2227
2244
2261
2278
2312
2329
2346
2363
2397
2414
2431
2448
2482
2499