Python Javtpoint
Python Javtpoint
Python tutorial provides basic and advanced concepts of Python. Our Python tutorial is
designed for beginners and professionals.
Python is a simple, easy to learn, powerful, high level and object-oriented programming
language.
Python is an interpreted scripting language also. Guido Van Rossum is known as the
founder of python programming.
Our Python tutorial includes all topics of Python Programming such as installation, control
statements, Strings, Lists, Tuples, Dictionary, Modules, Exceptions, Date and Time, File
I/O, Programs, etc. There are also given Python interview questions to help you better
understand the Python Programming.
Python Introduction
Python is a general purpose, dynamic, high level and interpreted programming language.
It supports Object Oriented programming approach to develop applications. It is simple
and easy to learn and provides lots of high-level data structures.
Python is easy to learn yet powerful and versatile scripting language which makes it
attractive for Application Development.
Python's syntax and dynamic typing with its interpreted nature, makes it an ideal language
for scripting and rapid application development.
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.
We don't need to use data types to declare variable because it is dynamically typed so we
can write a=10 to assign an integer value in an integer variable.
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 2 vs. Python 3
In most of the programming languages, whenever a new version releases, it supports the
features and syntax of the existing version of the language, therefore, it is easier for the
projects built in the language to switch in the newer version. However, in the case of
python, the two versions python 2 and python are very much different from each other.
1. Python 2 uses print as a statement and used as print "something" to print some
string on the console. On the other hand, Python 3 uses print as a function and
used as print("something") to print something on the console.
2. Python 2 uses the function raw_input() to accept the user's input. It returns the
string representing the value which has typed by the user. To convert it into the
integer, we need to use the int() function in python. On the other hand, Python 3
uses input() function which automatically interpreted the type of input entered by
the user. However, we can cast this value to any type by using primitive functions
(int(), str(), etc.).
3. In python 2, the implicit string type is ASCII whereas, in python 3, the implicit
string type is Unicode.
4. Python 3 doesn't contain the xrange() function of python 2. The xrange() is the
variant of range() function which returns a xrange object that works similar to Java
iterator. The range() returns a list for example the function range(0,3) contains 0,
1, 2.
5. There is also a small change made in Exception handling in python 3. It defines a
keyword as which is necessary to be used. We will discuss it in Exception handling
section of this tutorial.
Python Index
o Python continue
Python Programs
o Python pass
o Basic Python programs
Python Strings
o Python program to print "Hello
Prerequisite
Before learning Python, you must have the basic knowledge of programming concepts.
Audience
Our Python tutorial is designed to help beginners and professionals.
Problem
We assure that you will not find any problem in this Python tutorial. But if there is any
mistake, please post the problem in contact form.
Python Features
Python provides lots of features that are listed below.
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.
Python language is freely available at 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.
Python has a large and broad library and prvides rich set of module and functions for rapid
application development.
9) GUI Programming Support
10) Integrated
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.
We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, request, beautiful Soup, Feed
parser etc. It also provides Frameworks such as Django, Pyramid, Flask etc to design and
develop web based applications. Some important developments are: Python Wiki Engines,
Pocoo, Python Blog Software etc.
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.
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.
We can use Python to develop console based applications. For example: IPython.
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
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.
Type PATH as the variable name and set the path to the installation directory of the
python shown in the below image.
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.
Installation on Mac
To install python3 on MacOS, visit the link https://www.javatpoint.com/how-to-install-
python-on-mac and follow the instructions given in the tutorial.
Installation on CentOS
To install Python3 on CentOS, visit the link https://www.javatpoint.com/how-to-install-
python-on-centos and follow the instructions given in the tutorial.
Installation on Ubuntu
To install Python3 on Ubuntu, visit the link https://www.javatpoint.com/how-to-install-
python-in-ubuntu and follow the instructions given in the tutorial.
To open the interactive mode, open the terminal (or command prompt) and type python
(python3 in case if you have python2 and python3 both installed on your system).
It will open the following prompt where we can execute the python statement and check
their impact on the console.
Let's run a python statement to print the traditional hello world on the console. Python3
provides print() function to print some message on the console. We can pass the message
as a string into this function. Consider the following image.
Here, we get the message "Hello World !" printed on the console.
We need to write our code into a file which can be executed later. For this purpose, open
an editor like notepad, create a file named first.py (python used .py extension) and write
the following code in it.
Print ("hello world"); #here, we have used print() function to print the message on the c
onsole.
To run this file named as first.py, we need to run the following command on the
terminal.
$ python3 first.py
Hence, we get our output as the message Hello World ! is printed on the console.
JetBrains provides the most popular and a widely used cross-platform IDE PyCharm to
run the python programs.
PyCharm installation
As we have already stated, PyCharm is a cross-platform IDE, and hence it can be installed
on a variety of the operating systems. In this section of the tutorial, we will cover the
installation process of PyCharm on Windows, MacOS, CentOS, and Ubuntu.
Windows
Installing PyCharm on Windows is very simple. To install PyCharm on Windows operating
system, visit the link https://www.jetbrains.com/pycharm/download/download-
thanks.html?platform=windows to download the executable installer. Double clickthe
installer (.exe) file and install PyCharm by clicking next at each step.
CentOS
To install PyCharm on CentOS, visit the link https://www.javatpoint.com/how-to-install-
pycharm-on-centos. The link will guide you to install PyCharm on the CentOS.
MacOS
To install PyCharm on MacOS, visit the link https://www.javatpoint.com/how-to-install-
pycharm-on-mac. The link will guide you to install PyCharm on the MacOS.
Ubuntu
To install PyCharm on Ubuntu, visit the link https://www.javatpoint.com/how-to-install-
pycharm-in-ubuntu. The link will guide you to install PyCharm on Ubuntu.
In the upcoming section of the tutorial, we will use PyCharm to edit the python code.
Python Variables
Variable is a name which is used to refer memory location. Variable also known as identifier
and used to hold value.
In Python, we don't need to specify the type of variable because Python is a type infer
language and smart enough to get variable type.
Variable names can be a group of both letters and digits, but they have to begin with a
letter or an underscore.
It is recommended to use lowercase letters for variable name. Rahul and rahul both are
two different variables.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used
in the program. The rules to name an identifier are given below.
We don't need to declare explicitly variable in Python. When we assign any value to the
variable that variable is declared automatically.
Eg:
Output:
1. >>>
2. 10
3. ravi
4. 20000.67
5. >>>
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement which is also
known as multiple assignment.
We can apply multiple assignments in two ways either by assigning a single value to
multiple variables or assigning multiple values to multiple variables. Lets see given
examples.
Eg:
1. x=y=z=50
2. print iple
3. print y
4. print z
Output:
1. >>>
2. 50
3. 50
4. 50
5. >>>
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
1. >>>
2. 5
3. 10
4. 15
5. >>>
ii) Comments
a)Tokens:
o Tokens can be defined as a punctuator mark, reserved words and each individual
word in a statement.
o Token is the smallest unit inside the given program.
o Keywords.
o Identifiers.
o Literals.
o Operators.
Tuples:
o Tuple is another form of collection where different type of data can be stored.
o It is similar to list where data is separated by commas. Only the difference is that
list uses square bracket and tuple uses parenthesis.
o Tuples are enclosed in parenthesis and cannot be changed.
Eg:
1. >>> tuple=('rahul',100,60.4,'deepak')
2. >>> tuple1=('sanjay',10)
3. >>> tuple
4. ('rahul', 100, 60.4, 'deepak')
5. >>> tuple[2:]
6. (60.4, 'deepak')
7. >>> tuple1[0]
8. 'sanjay'
9. >>> tuple+tuple1
10. ('rahul', 100, 60.4, 'deepak', 'sanjay', 10)
11. >>>
Dictionary:
o Dictionary is a collection which works on a key-value pair.
o It works like an associated array where no two keys can be same.
o Dictionaries are enclosed by curly braces ({}) and values can be retrieved by
square bracket([]).
Eg:
1. >>> dictionary={'name':'charlie','id':100,'dept':'it'}
2. >>> dictionary
3. {'dept': 'it', 'name': 'charlie', 'id': 100}
4. >>> dictionary.keys()
5. ['dept', 'name', 'id']
6. >>> dictionary.values()
7. ['it', 'charlie', 100]
8. >>>
Python enables us to check the type of the variable used in the program. Python provides
us the type() function which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking
its type.
1. A=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a));
5. print(type(b));
6. print(type(c));
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Python provides various standard data types that define the storage method on each of
them. The data types defined in Python are given below.
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
In this section of the tutorial, we will give a brief introduction of the above data types. We
will discuss each one of them in detail later in this tutorial.
Numbers
Number stores numeric values. Python creates Number objects when a number is assigned
to a variable. For example;
Python allows us to use a lower-case L to be used with long integers. However, we must
always use an upper-case L to avoid confusion.
A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and
imaginary parts respectively).
String
The string can be defined as the sequence of characters represented in the quotation
marks. In python, we can use single, double, or triple quotes to define a string.
String handling in python is a straightforward task since there are various inbuilt functions
and operators provided.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as repetition operator as the operation "Python " *2 returns
"Python Python ".
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Lists are similar to arrays in C. However; the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets
[].
We can use slice [:] operators to access the data of the list. The concatenation operator
(+) and repetition operator (*) works with the list in the same way as they were working
with the strings.
Output:
[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of
the items of different data types. The items of the tuple are separated with a comma (,)
and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of
a tuple.
1. t = ("hi", "python", 2)
2. print (t[1:]);
3. print (t[0:1]);
4. print (t);
5. print (t + t);
6. print (t * 3);
7. print (type(t))
8. t[2] = "hi";
Output:
('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
Dictionary is an ordered set of a key-value pair of items. It is like an associative array or
a hash table where each key stores a specific value. Key can hold any primitive data type
whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma and enclosed in the curly braces
{}.
Output:
Python Keywords
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.
True False None and as
Python Literals
Literals can be defined as a data that is given in a variable or constant.
I. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as
well as double quotes for a String.
Eg:
"Aman" , '12345'
Types of Strings:
a).Single line String- Strings that are terminated within a single line are known as Single
line Strings.
Eg:
1. >>> text1='hello'
b).Multi line String- A piece of text that is spread along multiple lines is known as Multiple
line String.
Eg:
1. >>> text1='hello\
2. user'
3. >>> text1
4. 'hellouser'
5. >>>
Eg:
1. >>> str2='''''welcome
2. to
3. SSSIT'''
4. >>> print str2
5. welcome
6. to
7. SSSIT
8. >>>
II.Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four different
numerical types.
A Boolean literal can have any of the two values: True or False.
None is used to specify to that field that is not created. It is also used for end of lists in
Python.
Eg:
1. >>> val1=10
2. >>> val2=None
3. >>> val1
4. 10
5. >>> val2
6. >>> print val2
7. None
8. >>>
V.Literal Collections.
List:
o List contain items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by commas(,) and enclosed within a square
brackets([]). We can store different type of data in a List.
o Value stored in a List can be retrieved using the slice operator([] and [:]).
o The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.
Eg:
1. >>> list=['aman',678,20.4,'saurav']
2. >>> list1=[456,'rahul']
3. >>> list
4. ['aman', 678, 20.4, 'saurav']
5. >>> list[1:3]
6. [678, 20.4]
7. >>> list+list1
8. ['aman', 678, 20.4, 'saurav', 456, 'rahul']
9. >>> list1*2
10. [456, 'rahul', 456, 'rahul']
11. >>>
Python Operators
The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built
in a particular programming language. Python provides a variety of operators described
as follows.
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands. It
includes +(addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor
division), and exponent (**).
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand
is less than the second operand, the value result negative. For example, if a = 20, b
= 10 => a ? b = 10
/ (divide) It returns the quotient after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a/b = 2
* It is used to multiply one operand with the other. For example, if a = 20, b = 10 =>
(Multiplication) a * b = 200
% (reminder) It returns the reminder after dividing the first operand by the second operand. For
example, if a = 20,b = 10 => a%b = 0
// (Floor division) It gives the floor value of the quotient produced by dividing the two operands.
Comparison operator
Comparison operators are used to comparing the value of the two operands and returns
boolean true or false accordingly. The comparison operators are described in the following
table.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the
condition becomes true.
>= If the first operand is greater than or equal to the second operand, then
the condition becomes true.
<> If the value of two operands is not equal, then the condition becomes true.
> If the first operand is greater than the second operand, then the condition
becomes true.
< If the first operand is less than the second operand, then the condition
becomes true.
Operator Description
= It assigns the the value of the right expression to the left operand.
+= It increases the value of the left operand by the value of the right operand and
assign the modified value back to left operand. For example, if a = 10, b = 20
=> a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand
and assign the modified value back to left operand. For example, if a = 20, b
= 10 => a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand
and assign the modified value back to left operand. For example, if a = 10, b
= 20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and
assign the reminder back to left operand. For example, if a = 20, b = 10 =>
a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.
Bitwise operator
The bitwise operators perform bit by bit operation on the values of the two operands.
For example,
1. if a = 7;
2. b = 6;
3. then, binary (a) = 0111
4. binary (b) = 0011
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is
and) copied to the result. Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero otherwise the
resulting bit will be 1.
^ (binary The resulting bit will be 1 if both the bits are different otherwise the
xor) resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is
0, the resulting bit will be 1 and vice versa.
<< (left The left operand value is moved left by the number of bits present
shift) in the right operand.
>> (right The left operand is moved right by the number of bits present in the
shift) right operand.
Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision.
Python supports the following logical operators.
Operator Description
and If both the expression are true, then the condition will be true. If a and b
are the two expressions, a → true, b → true => a and b → true.
or If one of the expressions is true, then the condition will be true. If a and b
are the two 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.
Membership Operators
Python membership operators are used to check the membership of value inside a data
structure. If the value is present in the data structure, then the resulting value is true
otherwise it returns false.
Operator Description
not in It is evaluated to be true if the first operand is not found in the second
operand (list, tuple, or dictionary).
Identity Operators
Operator Description
is not It is evaluated to be true if the reference present at both side do not point
to the same object.
Operator Precedence
The precedence of the operators is important to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in python is
given below.
Operator Description
** The exponent operator is given priority over all the others used
in the expression.
<= < > >= Comparison operators (less then, less then equal to, greater
then, greater then equal to).
Python 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.
In case user wants to specify a single line comment, then comment must start with ?#?
Eg:
Output:
Hello Python
eg:
1. ''''' This
2. Is
3. Multipline comment'''
eg:
Output:
Hello Python
Statement Description
If - else The if-else statement is similar to if statement except the fact that,
Statement it 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.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If
two statements are at the same indentation level, then they are the part of the same
block.
Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.
Indentation is the most used part of the python language since it declares the block of
code. All the statements of one block are intended at the same level indentation. We will
see how the actual indentation takes place in decision making and other stuff in python.
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.
1. if expression:
2. statement
Example 1
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")
Output:
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Example 1 : Program to check whether a person is eligible
to vote or not.
1. age = int (input("Enter your age? "))
2. if age>=18:
3. print("You are eligible to vote !!");
4. else:
5. print("Sorry! you have to wait !!");
Output:
Output:
1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");
Output:
Python Loops
The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code
may need to be repeated several numbers of times.
For this purpose, The programming languages provide various types of loops which are
capable of repeating some specific code several numbers of times. Consider the following
diagram to understand the working of a loop statement.
Advantages of loops
There are the following advantages of loops in Python.
Loop Description
Statement
for loop The for loop is used in the case where we need to execute some part
of the code until the given condition is satisfied. The for loop is also
called as a per-tested loop. It is better to use for loop if the number
of iteration is known in advance.
while loop The while loop is to be used in the scenario where we don't know the
number of iterations in advance. The block of statements is executed
in the while loop until the condition specified in the while loop is
satisfied. It is also called a pre-tested loop.
do-while The do-while loop continues until a given condition satisfies. It is also
loop called post tested loop. It is used when it is necessary to execute the
loop at least once (mostly menu driven programs).
Example
1. i=1
2. n=int(input("Enter the number up to which you want to print the natural numbers?"))
3. for i in range(0,10):
4. print(i,end = ' ')
Output:
0 1 2 3 4 5 6 7 8 9
Python for loop example : printing the table of the given number
1. i=1;
2. num = int(input("Enter a number:"));
3. for i in range(1,11):
4. 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
Example 1
1. n = int(input("Enter the number of rows you want to print?"))
2. i,j=0,0
3. for i in range(0,n):
4. print()
5. for j in range(0,i+1):
6. print("*",end="")
Output:
Example 1
1. for i in range(0,5):
2. print(i)
3. 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
Example 2
1. for i in range(0,5):
2. print(i)
3. break;
4. else:print("for loop is exhausted");
5. print("The loop is broken due to break statement...came out of loop")
In the above example, the loop is broken due to break statement therefore the else
statement will not be executed. The statement present immediate next to else block will
be executed.
Output:
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.
1. while expression:
2. 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
1. i=1;
2. while i<=10:
3. print(i);
4. i=i+1;
Output:
1
2
3
4
5
6
7
8
9
10
Example 2
1. i=1
2. number=0
3. b=9
4. number = int(input("Enter the number?"))
5. while i<=10:
6. print("%d X %d = %d \n"%(number,i,number*i));
7. i = i+1;
Output:
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
Example 1
1. while (1):
2. print("Hi! we are inside the infinite while loop");
Output:
Example 2
1. var = 1
2. while var != 2:
3. i = int(input("Enter the number?"))
4. print ("Entered value is %d"%(i))
Output:
1. i=1;
2. while i<=5:
3. print(i)
4. i=i+1;
5. else:print("The while loop exhausted");
Output:
1
2
3
4
5
The while loop exhausted
Example 2
1. i=1;
2. while i<=5:
3. print(i)
4. i=i+1;
5. if(i==3):
6. break;
7. else:print("The while loop exhausted");
Output:
1
2
The break is commonly used in the cases where we need to break the loop for a given
condition.
1. #loop statements
2. break;
Example 1
Example 2
1. list =[1,2,3,4]
2. count = 1; 1. str = "python"
3. for i in list: 2. for i in str:
4. if i == 4: 3. if i == 'o':
5. print("item matched") 4. break
6. count = count + 1; 5. print(i);
7. break
Output:
8. print("found at",count,"location");
p
Output: y
t
item matched h
found at 2 location
Output:
Example 3
1. n=2
2. while 1:
3. i=1;
4. while i<=10:
5. print("%d X %d = %d\n"%(n,i,n*i));
6. i = i+1;
7. choice = int(input("Do you want to continue printing the table, press 0 for no?"))
8. if choice == 0:
9. break;
10. n=n+1
Output:
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
1. #loop statements
2. continue;
3. #the code to be skipped
Example 1
1. i = 0;
2. while i!=10:
3. print("%d"%i);
4. continue;
5. i=i+1;
Output:
infinite loop
Example 2
1. i=1; #initializing a local variable
2. #starting a loop from 1 to 10
3. for i in range(1,11):
4. if i==5:
5. continue;
6. print("%d"%i);
Output:
1
2
3
4
6
7
8
9
10
Pass Statement
The pass statement is a null operation since nothing happens when it is executed. It is
used in the cases where a statement is syntactically needed but we don't want to use any
executable statement at its place.
For example, it can be used while overriding a parent class method in the subclass but
don't want to give its specific implementation in the subclass.
Pass is also used where the code will be written somewhere but not yet written in the
program file.
Example
1. list = [1,2,3,4,5]
2. flag = 0
3. for i in list:
4. print("Current element:",i,end=" ");
5. if i==3:
6. pass;
7. print("\nWe are inside pass block\n");
8. flag = 1;
9. if flag==1:
10. print("\nCame out of pass\n");
11. flag=0;
Output:
Python String
Till now, we have discussed numbers as the standard data types in python. In this section of
the tutorial, we will discuss the most popular data type in python i.e., string.
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.
Here, if we check the type of the variable str using a python script
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.
As shown in python, the slice operator [] is used to access the individual characters of the
string. However, we can use the : (colon) operator in python to access the substring. Consider
the following example.
Here, we must notice that the upper range given in the slice operator is always exclusive i.e.,
if str = 'python' is given, then str[1:3] will always include str[1] = 'p', str[2] = 'y', str[3] = 't' and
nothing else.
Reassigning strings
Updating the content of the strings is as easy as assigning it to a new string. The string object
doesn't support item assignment i.e., A string can only be replaced with a new string since its
content cannot be partially replaced. Strings are immutable in python.
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
However, in example 1, the string str can be completely assigned to a new content as specified
in the following example.
Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
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 range slice operator. It is used to access the characters from
the specified range.
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.
Example
Consider the following example to understand the real use of Python operators.
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. 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
1. Integer = 10;
2. Float = 1.290
3. String = "Ayush"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f
\nHi I am string ... My value is %s"%(Integer,Float,String));
Output:
decode(encoding = 'UTF8', errors = Decodes the string using codec registered for
'strict') encoding.
rpartition()
Python List
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 [].
If we try to print the type of L1, L2, and L3 then it will come out to be a list.
Lets consider a proper example to define a list and printing its values.
Output:
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.
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 immutable 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.
1. List = [1, 2, 3, 4, 5, 6]
2. print(List)
3. List[2] = 10;
4. print(List)
5. List[1:3] = [89, 78]
6. 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.
1. List = [0,1,2,3,4]
2. print(List)
3. del List[0]
4. print(List)
5. del List[3]
6. print(List)
Output:
[0, 1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3]
Iteration The for loop is used to iterate over the list for i in l1:
elements. print(i)
Output
1
2
3
4
Output:
John
David
James
Jonathan
Consider the following example in which, we are taking the elements of the list from the
user and printing the list on the console.
1. l =[];
2. n = int(input("Enter the number of elements in the list")); #Number of elements will be
entered by the user
3. for i in range(0,n): # for loop to take the input
4. l.append(input("Enter the item?")); # The input is taken from the user and added to t
he list as the item
5. print("printing the list items....");
6. for i in l: # traversal loop to print the list items
7. print(i, end = " ");
Output:
Output:
SN Function Description
SN Function Description
7 list.insert(index, The object is inserted into the list at the specified index.
obj)
Python Tuple
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.
Example
1. tuple1 = (10, 20, 30, 40, 50, 60)
2. print(tuple1)
3. count = 0
4. for i in tuple1:
5. print("tuple1[%d] = %d"%(count, i));
Output:
Output:
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.
1. T3 = ()
The tuple having a single value must include a comma as given below.
1. 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.
ADVERTISEMENT
We will see all these aspects of tuple in this section of the tutorial.
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 cannot 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.
1. tuple1 = (1, 2, 3, 4, 5, 6)
2. print(tuple1)
3. del tuple1[0]
4. print(tuple1)
5. del tuple1
6. 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.
Output:
5
2
SN Function Description
1. Using tuple instead of list gives us a clear idea that tuple data is constant and must not
be changed.
2. Tuple can simulate dictionary without keys. Consider the following nested structure
which can be used as a dictionary.
3. Tuple can be used as the key inside dictionary due to its immutable nature.
List VS Tuple
SN List Tuple
1 The literal syntax of list is shown by The literal syntax of the tuple is shown by
the []. the ().
3 The List has the variable length. The tuple has the fixed length.
4 The list provides more functionality The tuple provides less functionality than
than tuple. the list.
5 The list Is used in the scenario in The tuple is used in the cases where we
which we need to store the simple need to store the read-only collections
collections with no constraints where i.e., the value of the items can not be
the value of the items can be changed. It can be used as the key inside
changed. the dictionary.
Lets see an example of how can we store the tuple inside the list.
1. Employees = [(101, "Ayush", 22), (102, "john", 29), (103, "james", 45), (104, "Ben", 34
)]
2. print("----Printing list----");
3. for i in Employees:
4. print(i)
5. Employees[0] = (110, "David",22)
6. print();
7. print("----Printing list after modification----");
8. for i in Employees:
9. print(i)
Output:
----Printing list----
(101, 'Ayush', 22)
(102, 'john', 29)
(103, 'james', 45)
(104, 'Ben', 34)
Python Set
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.
Output:
Output:
Example:
1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nAdding other months to the set...");
5. Months.add("July");
6. Months.add("August");
7. print("\nPrinting the modified set...");
8. print(Months)
9. print("\nlooping through the set elements ... ")
10. for i in Months:
11. print(i)
Output:
To add more than one item in the set, Python provides the update() method.
Example
1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nupdating the original set ... ")
5. Months.update(["July","August","September","October"]);
6. print("\nprinting the modified set ... ")
7. print(Months);
Output:
Example
1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving some months from the set...");
5. Months.discard("January");
6. Months.discard("May");
7. print("\nPrinting the modified set...");
8. print(Months)
9. print("\nlooping through the set elements ... ")
10. for i in Months:
11. print(i)
Output:
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
1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving some months from the set...");
5. Months.remove("January");
6. Months.remove("May");
7. print("\nPrinting the modified set...");
8. print(Months)
Output:
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.
Output:
Python provides the clear() method to remove all the items from the set.
Output:
If the key to be deleted from the set using discard() doesn't exist in the set, the python
will not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't exist in
the set, the python will give the error.
Example
1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving items through discard() method...");
5. Months.discard("Feb"); #will not give an error although the key feb is not available in th
e set
6. print("\nprinting the modified set...")
7. print(Months)
8. print("\nRemoving items through remove() method...");
9. Months.remove("Jan") #will give an error as the key jan is not available in the set.
10. print("\nPrinting the modified set...")
11. print(Months)
Output:
Output:
Python also provides the union() method which can also be used to calculate the union
of two sets. Consider the following example.
Output:
Output:
{'Martin', 'David'}
Output:
{'Martin', 'David'}
Output:
{'castle'}
Output:
{'Thursday', 'Wednesday'}
Output:
{'Thursday', 'Wednesday'}
Set comparisons
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets
by using which we can check whether a set is subset, superset, or equivalent to other set.
The boolean true or false is returned depending upon the items present inside the sets.
Output:
True
False
False
FrozenSets
The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen
set can not be changed and therefore it can be used as a key in dictionary.
The elements of the frozen set can not be changed after the creation. We cannot change
or append the content of the frozen sets by using the methods like add() or remove().
The frozenset() method is used to create the frozenset object. The iterable sequence is
passed into this method which is converted into the frozen set as a return type of the
method.
1. Frozenset = frozenset([1,2,3,4,5])
2. print(type(Frozenset))
3. print("\nprinting the content of frozen set...")
4. for i in Frozenset:
5. print(i);
6. Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after
creation
Output:
<class 'frozenset'>
Output:
<class 'dict'>
<class 'frozenset'>
Name
Country
ID
SN Method Description
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.
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.
Output
<class 'dict'>
printing Employee data ....
{'Age': 29, 'salary': 25000, 'Name': 'John', 'Company': 'GOOGLE'}
However, the values can be accessed in the dictionary by using the keys as keys are unique in
the dictionary.
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.
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}
Output:
<class 'dict'>
printing Employee data ....
{'Age': 29, 'Company': 'GOOGLE', 'Name': 'John', 'salary': 25000}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
Traceback (most recent call last):
File "list.py", line 13, in <module>
print(Employee)
NameError: name 'Employee' is not defined
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
Output:
Name
Company
salary
Age
Example 2
#for loop to print all the values of the dictionary
Output:
29
GOOGLE
John
25000
Example 3
#for loop to print the values of the dictionary by using values() method.
Output:
GOOGLE
25000
John
29
Example 4
#for loop to print the items of the dictionary by using items() method.
Output:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
Output:
Salary 25000
Company GOOGLE
Name Johnn
Age 29
2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuple as
the key but we can not use any mutable object like the list as the key in the dictionary.
Output:
SN Function Description
1 cmp(dict1, It compares the items of both the dictionary and returns true
dict2) if the first dictionary values are greater than the second
dictionary, otherwise it returns false.
SN Method Description
len()
popItem()
pop()
count()
index()
Python Functions
Functions are the most important aspect of an application. A function can be defined as
the organized block of reusable code which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}. A function can
be called multiple times to provide reusability and modularity to the python program.
In other words, we can say that the collection of functions creates a program. The function
is also known as procedure or subroutine in other programming languages.
Python provide us various inbuilt functions like range() or print(). Although, the user can
create its functions which can be called user-defined functions.
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call python functions any number of times in a program and from any place
in a program.
o We can track a large python program easily when it is divided into multiple
functions.
o Reusability is the main achievement of python functions.
o However, Function calling is always overhead in a python program.
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function
in python is given below.
1. def my_function():
2. function-suite
3. return <expression>
The function block is started with the colon (:) and all the same level block statements
remain at the same indentation.
A function can accept any number of parameters that must be the same in the definition
and function calling.
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.
1. def hello_world():
2. print("hello world")
3.
4. 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
1. #defining the function
2. def func (name):
3. print("Hi ",name);
4.
5. #calling the function
6. func("Ayush")
Example 2
1. #python function to calculate the sum of two variables
2. #defining the function
3. def sum (a,b):
4. return a+b;
5.
6. #taking values from the user
7. a = int(input("Enter a: "))
8. b = int(input("Enter b: "))
9.
10. #printing the sum of a and b
11. print("Sum = ",sum(a,b))
Output:
Enter a: 10
Enter b: 20
Sum = 30
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.
Output:
Output:
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
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.
Example 1
1. #the argument name is the required argument to the function func
2. def func(name):
3. message = "Hi "+name;
4. return message;
5. name = input("Enter the name?")
6. print(func(name))
Output:
Example 2
1. #the function simple_interest accepts three arguments and returns the simple interest a
ccordingly
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. p = float(input("Enter the principle amount? "))
5. r = float(input("Enter the rate of interest? "))
6. t = float(input("Enter the time in years? "))
7. print("Simple Interest: ",simple_interest(p,r,t))
Output:
Example 3
1. #the function calculate returns the sum of two arguments a and b
2. def calculate(a,b):
3. return a+b
4. calculate(10) # this causes an error as we are missing a required arguments b.
Output:
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
1. #function func is called with the name and message as the keyword arguments
2. def func(name,message):
3. print("printing the message with",name,"and ",message)
4. func(name = "John",message="hello") #name and message is copied with the values Jo
hn and hello respectively
Output:
Output:
If we provide the different name of arguments at the time of function call, an error will be
thrown.
Example 3
1. #The function simple_interest(p, t, r) is called with the keyword arguments.
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4.
5. print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900)) # doesn't fi
nd the exact match of the name of the arguments (keywords)
Output:
The python allows us to provide the mix of the required arguments and keyword
arguments at the time of function call. However, the required argument must not be given
after the keyword argument, i.e., once the keyword argument is encountered in the
function call, the following arguments must also be the keyword arguments.
Example 4
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello",name2="David") #the first argument is not the keyword ar
gument
Output:
The following example will cause an error due to an in-proper mix of keyword and required
arguments being passed in the function call.
Example 5
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello","David")
Output:
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
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however the d
efault value of age is considered in the function
Output:
Example 2
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however the d
efault value of age is considered in the function
4. printme(age = 10,name="David") #the value of age is overwritten here, 10 will be print
ed as age
Output:
However, at the function definition, we have to define the variable with * (star) as
*<variable - name >.
Example
1. def printme(*names):
2. print("type of passed argument is ",type(names))
3. print("printing the passed arguments...")
4. for name in names:
5. print(name)
6. printme("john","David","smith","nick")
Output:
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
1. def print_message():
2. message = "hello !! I am going to print a message." # the variable message is local t
o the function itself
3. print(message)
4. print_message()
5. print(message) # this will cause an error since a local variable cannot be accessible her
e.
Output:
Example 2
1. def calculate(*args):
2. sum=0
3. for arg in args:
4. sum = sum +arg
5. print("The sum is",sum)
6. sum=0
7. calculate(10,20,30) #60 will be printed as the sum
8. print("Value of sum outside the function:",sum) # 0 will be printed
Output:
The sum is 60
Value of sum outside the function: 0
The anonymous function contains a small piece of code. It simulates inline functions of C
and C++, but it is not exactly an inline function.
Example 1
1. x = lambda a:a+10 # a is an argument and a+10 is an expression which got evaluated
and returned.
2. print("sum = ",x(20))
Output:
sum = 30
Example 2
Multiple arguments to Lambda function
1. x = lambda a,b:a+b # a and b are the arguments and a+b is the expression which gets
evaluated and returned.
2. print("sum = ",x(20,10))
Output:
sum = 30
Example 1
1. #the function table(n) prints the table of n
2. def table(n):
3. return lambda a:a*n; # a will contain the iteration variable i and a multiple of n is r
eturned at each function call
4. n = int(input("Enter the number?"))
5. b = table(n) #the entered number is passed into the function table. b will contain a lamb
da function which is called again and again with the iteration variable i
6. for i in range(1,11):
7. print(n,"X",i,"=",b(i)); #the lambda function b is called with the iteration variable i,
Output:
Example 2
Use of lambda function with filter
Output:
[3, 123]
Example 3
Use of lambda function with map
Output:
Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on the
console, and since the memory is volatile, it is impossible to recover the programmatically
generated data again and again.
However, if we need to do so, we may store it onto the local file system which is volatile
and can be accessed every time. Here, comes the need of file handling.
In this section of the tutorial, we will learn all about file handling in python including,
creating a file, opening a file, closing a file, writing and appending the file, etc.
Opening a file
Python provides the open() function which accepts two arguments, file name and access
mode in which the file is accessed. The function returns a file object which can be used to
perform various operations like reading, writing, etc.
The files can be accessed using various modes like read, write, or append. The following
are the details about the access mode to open a file.
SN Access Description
mode
2 rb It opens the file to read only in binary format. The file pointer exists
at the beginning of the file.
3 r+ It opens the file to read and write both. The file pointer exists at
the beginning of the file.
4 rb+ It opens the file to read and write both in binary format. The file
pointer exists at the beginning of the file.
6 wb It opens the file to write only in binary format. It overwrites the file
if it exists previously or creates a new one if no file exists with the
same name. The file pointer exists at the beginning of the file.
7 w+ It opens the file to write and read both. It is different from r+ in the
sense that it overwrites 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.
8 wb+ It opens the file to write and read both in binary format. The file
pointer exists at the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at the
end of the previously written file if exists any. It creates a new file
if no file exists with the same name.
10 ab It opens the file in the append mode in binary format. The pointer
exists at the end of the previously written file. It creates a new file
in binary format if no file exists with the same name.
11 a+ It opens a file to append and read both. The file pointer remains at
the end of the file if a file exists. It creates a new file if no file exists
with the same name.
12 ab+ It opens a file to append and read both in binary format. The file
pointer remains at the end 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
1. #opens the file file.txt in read mode
2. fileptr = open("file.txt","r")
3.
4. if fileptr:
5. print("file is opened successfully")
Output:
<class '_io.TextIOWrapper'>
file is opened successfully
We can perform any operation on the file externally in the file system is the file is opened in
python, hence it is good practice to close the file once all the operations are done.
1. fileobject.close()
Example
1. # opens the file file.txt in read mode
2. fileptr = open("file.txt","r")
3.
4. if fileptr:
5. print("file is opened successfully")
6.
7. #closes the opened file
8. fileptr.close()
1. fileobj.read(<count>)
Here, the count is the number of bytes to be read from the file starting from the beginning of
the file. If the count is not specified, then it may read the content of the file until the end.
Example
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file.txt","r");
3.
4. #stores all the data of the file into the variable content
5. content = fileptr.read(9);
6.
7. # prints the type of the data stored in the file
8. print(type(content))
9.
10. #prints the content of the file
11. print(content)
12.
13. #closes the opened file
14. fileptr.close()
Output:
<class 'str'>
Hi, I am
Read Lines of the file
Python facilitates us to read the file line by line by using a function readline(). The readline()
method reads the lines of the file from the beginning, i.e., if we use the readline() method two
times, then we can get the first two lines of the file.
Consider the following example which contains a function readline() that reads the first line of
our file "file.txt" containing three lines.
Example
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file.txt","r");
3.
4. #stores all the data of the file into the variable content
5. content = fileptr.readline();
6.
7. # prints the type of the data stored in the file
8. print(type(content))
9.
10. #prints the content of the file
11. print(content)
12.
13. #closes the opened file
14. fileptr.close()
Output:
<class 'str'>
Hi, I am the file and being used as
Example
1. #open the file.txt in read mode. causes an error if no such file exists.
2.
3.
4. fileptr = open("file.txt","r");
5.
6. #running a for loop
7. for i in fileptr:
8. print(i) # i contains each line of the file
Output:
a: It will append the existing file. The file pointer is at the end of the file. It creates a new file
if no file exists.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
Example 1
1. #open the file.txt in append mode. Creates a new file if no such file exists
.
2. fileptr = open("file.txt","a");
3.
4. #appending the content to the file
5. fileptr.write("Python is the modern day language. It makes things so simp
le.")
6.
7.
8. #closing the opened file
9. fileptr.close();
File.txt:
Now, we can check that all the previously written content of the file is overwritten with the
new text we have passed.
File.txt:
a: It creates a new file with the specified name if no such file exists. It appends the content to
the file if the file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites the existing
file.
Example
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","x");
3.
4. print(fileptr)
5.
6. if fileptr:
7. print("File created successfully");
Output:
File created successfully
The advantage of using with statement is that it provides the guarantee to close the file
regardless of how the nested block exits.
It is always suggestible to use the with statement in the case of file s because, if the break,
return, or exception occurs in the nested block of code then it automatically closes the file. It
doesn't let the file to be corrupted.
Example
1. with open("file.txt",'r') as f:
2. content = f.read();
3. print(content)
Output:
Example
1. # open the file file2.txt in read mode
2. fileptr = open("file2.txt","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",fileptr.tell())
6.
7. #reading the content of the file
8. content = fileptr.read();
9.
10. #after the read operation file pointer modifies. tell() returns the loc
ation of the fileptr.
11.
12. print("After reading, the filepointer is at:",fileptr.tell())
Output:
For this purpose, the python provides us the seek() method which enables us to modify the file
pointer position externally.
1. <file-ptr>.seek(offset[, from)
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved. If it is set to 0,
the beginning of the file is used as the reference position. If it is set to 1, the current position
of the file pointer is used as the reference position. If it is set to 2, the end of the file pointer is
used as the reference position.
Example
1. # open the file file2.txt in read mode
2. fileptr = open("file2.txt","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",fileptr.tell())
6.
7. #changing the file pointer location to 10.
8. fileptr.seek(10);
9.
10. #tell() returns the location of the fileptr.
11. print("After reading, the filepointer is at:",fileptr.tell())
Output:
Python os module
The os module provides us the functions that are involved in file processing operations like
renaming, deleting, etc.
1. rename(?current-name?, ?new-name?)
Example
1. import os;
2.
3. #rename file2.txt to file3.txt
4. os.rename("file2.txt","file3.txt")
1. remove(?file-name?)
Example
1. import os;
2.
3. #deleting the file named file3.txt
4. os.remove("file3.txt")
Example
1. import os;
2.
3. #creating a new directory with the name new
4. os.mkdir("new")
1. chdir("new-directory")
Example
1. import os;
2.
3. #changing the current working directory to new
4.
5. os.chdir("new")
1. os.getcwd()
Example
1. import os;
2.
3. #printing the current working directory
4. print(os.getcwd())
Deleting directory
The rmdir() method is used to delete the specified directory.
Example
1. import os;
2.
3. #removing the new directory
4. os.rmdir("new")
The check_call() method of module subprocess is used to execute a python script and write
the output of that script to a file.
The following example contains two python scripts. The script file1.py executes the script
file.py and writes its output to the text file output.txt
file.py:
1. temperatures=[10,-20,-289,100]
2. def c_to_f(c):
3. if c< -273.15:
4. return "That temperature doesn't make sense!"
5. else:
6. f=c*9/5+32
7. return f
8. for t in temperatures:
9. print(c_to_f(t))
file.py:
1. import subprocess
2.
3. with open("output.txt", "wb") as f:
4. subprocess.check_call(["python", "file.py"], stdout=f)
Output:
50
-4
That temperature doesn't make sense!
212
SN Method Description
7 File.readline([size]) It reads one line from the file and places the file
pointer to the beginning of the new line.
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.
Here, we need to include this module into our main module to call the method displayMsg()
defined in the module named 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.
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:
1. import file;
2. name = input("Enter the name?")
3. file.displayMsg(name)
Output:
Consider the following module named as calculation which contains three functions as
summation, multiplication, and divide.
calculation.py:
Main.py:
Output:
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.
Example
1. #the module calculation of previous example is imported in this example as cal.
2. import calculation as cal;
3. a = int(input("Enter a?"));
4. b = int(input("Enter b?"));
5. print("Sum = ",cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
Example
1. import json
2.
3. List = dir(json)
4.
5. print(List)
Output:
1. reload(<module-name>)
for example, to reload the module calculation defined in the previous example, we must
use the following line of code.
1. reload(calculation)
Scope of variables
In Python, variables are associated with two types of scopes. All the variables defined in
a module contain the global scope unless or until it is defined within a function.
All the variables defined inside a function contain a local scope that is limited to this
function itself. We can not access a local variable globally.
If two variables are defined with the same name with the two different scopes, i.e., local
and global, then the priority will always be given to the local variable.
Consider the following example.
Example
1. name = "john"
2. def print_name(name):
3. print("Hi",name) #prints the name that is local to this function only.
4. name = input("Enter the name?")
5. print_name(name)
Output:
Hi David
Python packages
The packages in python facilitate the developer with the application development
environment by providing a hierarchical directory structure where a package contains sub-
packages, modules, and sub-modules. The packages are used to categorize the application
level code efficiently.
Let's create a package named Employees in your home directory. Consider the following
steps.
2. Create a python source file with name ITEmployees.py on the path /home/Employees.
ITEmployees.py
1. def getITNames():
2. List = ["John", "David", "Nick", "Martin"]
3. return List;
3. Similarly, create one more python file with name BPOEmployees.py and create a
function getBPONames().
4. Now, the directory Employees which we have created in the first step contains two
python modules. To make this directory a package, we need to include one more file here,
that is __init__.py which contains the import statements of the modules defined in this
directory.
__init__.py
6. To use the modules defined inside the package Employees, we must have to import this
in our python source file. Let's create a simple python source file at our home directory
(/home) which uses the modules defined in this package.
Test.py
1. import Employees
2. print(Employees.getNames())
Output:
We can have sub-packages inside the packages. We can nest the packages up to any level
depending upon the application requirements.
The following image shows the directory structure of an application Library management
system which contains three sub-packages as Admin, Librarian, and Student. The sub-
packages contain the python modules.
Python 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 the that.
Common Exceptions
A list of common exceptions that can be thrown from a normal python program is given
below.
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
Syntax
1. try:
2. #block of code
3.
4. except Exception1:
5. #block of code
6.
7. except Exception2:
8. #block of code
9.
10. #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.
1. try:
2. #block of code
3.
4. except Exception1:
5. #block of code
6.
7. else:
8. #this code executes if no except block is executed
Example
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b;
5. print("a/b = %d"%c)
6. except Exception:
7. print("can't divide by zero")
8. else:
9. print("Hi I am else block")
Output:
Enter a:10
Enter b:2
a/b = 5
Hi I am else block
Example
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b;
5. print("a/b = %d"%c)
6. except:
7. print("can't divide by zero")
8. else:
9. 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
1. try:
2. #this will throw an exception if the file doesn't exist.
3. fileptr = open("file.txt","r")
4. except IOError:
5. print("File not found")
6. else:
7. print("The file opened successfully")
8. fileptr.close()
Output:
Syntax
1. try:
2. #block of code
3.
4. except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)
5. #block of code
6.
7. else:
8. #block of code
Example
1. try:
2. a=10/0;
3. except ArithmeticError,StandardError:
4. print "Arithmetic Exception"
5. else:
6. 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.
syntax
1. try:
2. # block of code
3. # this may throw an exception
4. finally:
5. # block of code
6. # this will always be executed
Example
1. try:
2. fileptr = open("file.txt","r")
3. try:
4. fileptr.write("Hi I am good")
5. finally:
6. fileptr.close()
7. print("file closed")
8. except:
9. 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
1. 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
1. try:
2. age = int(input("Enter the age?"))
3. if age<18:
4. raise ValueError;
5. else:
6. print("the age is valid")
7. except ValueError:
8. print("The age is not valid")
Output:
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.
Example
1. class ErrorInCode(Exception):
2. def __init__(self, data):
3. self.data = data
4. def __str__(self):
5. return repr(self.data)
6.
7. try:
8. raise ErrorInCode(2000)
9. except ErrorInCode as ae:
10. print("Received error:", ae.data)
Output:
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.
In this section of the tutorial, we will discuss how to work with the date and time objects
in python.
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.
Example
1. import time;
2.
3. #prints the number of ticks spent since 12 AM, 1st January 1970
4.
5. print(time.time())
Output:
1545124460.9151757
Example
1. import time;
2.
3. #returns a time tuple
4.
5. print(time.localtime(time.time()))
Output:
Time tuple
The time is treated as the tuple of 9 numbers. Let's look at the members of the time tuple.
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
Example
1. import time;
2.
3. #returns the formatted time
4.
5. print(time.asctime(time.localtime(time.time())))
Output:
Example
1. import time
2. for i in range(0,5):
3. print(i)
4. #Each element will be printed after 1 second
5. time.sleep(1)
Output:
0
1
2
3
4
To work with dates as date objects, we have to import datetime module into the python
source code.
Consider the following example to get the datetime object representation for the current
time.
Example
1. import datetime;
2.
3. #returns the current datetime object
4.
5. print(datetime.datetime.now())
Output:
2018-12-18 16:16:45.462778
Example
1. import datetime;
2.
3. #returns the datetime object for the specified date
4.
5. print(datetime.datetime(2018,12,10))
Output:
2018-12-10 00:00:00
We can also specify the time along with the date to create the datetime object. Consider
the following example.
Example
1. import datetime;
2.
3. #returns the datetime object for the specified time
4.
5. print(datetime.datetime(2018,12,10,14,15,10))
Output:
2018-12-10 14:15:10
Comparison of two dates
We can compare two dates by using the comparison operators like >, >=, <, and <=.
Example
1. from datetime import datetime as dt
2. #Compares the time. If the time is in between 8AM and 4PM, then it prints working hour
s otherwise it prints fun hours
3. if dt(dt.now().year,dt.now().month,dt.now().day,8)<dt.now()<dt(dt.now().year,dt.now(
).month,dt.now().day,16):
4. print("Working hours....")
5. else:
6. print("fun hours")
Output:
fun hours
Consider the following example to print the Calendar of the last month of 2018.
Example
1. import calendar;
2. cal = calendar.month(2018,12)
3. #printing the calendar of December 2018
4. print(cal)
Output:
Printing the calendar of whole year
The prcal() method of calendar module is used to print the calendar of the whole year.
The year of which the calendar is to be printed must be passed into this method.
Example
1. import calendar
2.
3. #printing the calendar of the year 2019
4. calendar.prcal(2019)
Output:
Python Regular Expressions
The regular expressions can be defined as the sequence of characters which are used to
search for a pattern in a string. The module re provides the support to use regex in the
python program. The re module throws an exception if there is some error while using the
regular expression.
1. import re
Regex Functions
The following regex functions are used in the python.
SN Function Description
1 match This method matches the regex pattern in the string with the
optional flag. It returns true if 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.
Meta-Characters
Metacharacter is a character with the specified meaning.
Special Sequences
Special sequences are the sequences containing \ followed by one of the characters.
Character Description
\S It returns a match if the string doesn't contain any white space character.
\Z Returns a match if the specified characters are at the end of the string.
Sets
A set is a group of characters given inside a pair of square brackets. It represents the
special meaning.
SN Set Description
Example
1. import re
2.
3. str = "How are you. How is everything"
4.
5. matches = re.findall("How", str)
6.
7. print(matches)
8.
9. print(matches)
Output:
['How', 'How']
Example
1. import re
2.
3. str = "How are you. How is everything"
4.
5. matches = re.search("How", str)
6.
7. print(type(matches))
8.
9. print(matches) #matches is the search object
Output:
<class '_sre.SRE_Match'>
<_sre.SRE_Match object; span=(0, 3), match='How'>
1. span(): It returns the tuple containing the starting and end position of the match.
2. string(): It returns a string passed into the function.
3. group(): The part of the string is returned where the match is found.
Example
1. import re
2.
3. str = "How are you. How is everything"
4.
5. matches = re.search("How", str)
6.
7. print(matches.span())
8.
9. print(matches.group())
10.
11. print(matches.string)
Output:
(0, 3)
How
How are you. How is everything
Python OOPs Concepts
Like other general purpose languages, python is also an object-oriented language since
its beginning. Python is an object-oriented programming language. It allows us to develop
applications using an Object Oriented approach. In Python, we can easily create and use
classes and objects.
o Object
o Class
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o 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
1. class ClassName:
2. <statement-1>
3. .
4. .
5. <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.
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
3. It simulates the real world entity. So It doesn't simulate the real world. It
real-world problems can be easily works on step by step instructions
solved through oops. divided into small parts called
functions.
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.
In this section of the tutorial, we will discuss creating classes and objects in python. We
will also talk about how an attribute is accessed by using the class object.
Syntax
1. class ClassName:
2. #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
1. class Employee:
2. id = 10;
3. name = "ayush"
4. def display (self):
5. 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.
1. <object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined in the above
example.
Example
1. class Employee:
2. id = 10;
3. name = "John"
4. def display (self):
5. print("ID: %d \nName: %s"%(self.id,self.name))
6. emp = Employee()
7. emp.display()
Output:
ID: 10
Name: ayush
Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.
1. Parameterized Constructor
2. 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.
Example
1. class Employee:
2. def __init__(self,name,id):
3. self.id = id;
4. self.name = name;
5. def display (self):
6. print("ID: %d \nName: %s"%(self.id,self.name))
7. emp1 = Employee("John",101)
8. emp2 = Employee("David",102)
9.
10. #accessing display() method to print employee 1 information
11.
12. emp1.display();
13.
14. #accessing display() method to print employee 2 information
15. emp2.display();
Output:
ID: 101
Name: John
ID: 102
Name: David
Output:
Output:
SN Function Description
Example
1. class Student:
2. def __init__(self,name,id,age):
3. self.name = name;
4. self.id = id;
5. self.age = age
6.
7. #creates the object of the class Student
8. s = Student("John",101,22)
9.
10. #prints the attribute name of the object s
11. print(getattr(s,'name'))
12.
13. # reset the value of attribute age to 23
14. setattr(s,"age",23)
15.
16. # prints the modified value of age
17. print(getattr(s,'age'))
18.
19. # prints true if the student contains the attribute with name id
20.
21. print(hasattr(s,'id'))
22. # deletes the attribute age
23. delattr(s,'age')
24.
25. # this will give an error since the attribute age has been deleted
26. print(s.age)
Output:
John
23
True
AttributeError: 'Student' object has no attribute 'age'
SN Attribute Description
Example
1. class Student:
2. def __init__(self,name,id,age):
3. self.name = name;
4. self.id = id;
5. self.age = age
6. def display_details(self):
7. print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
8. s = Student("John",101,22)
9. print(s.__doc__)
10. print(s.__dict__)
11. print(s.__module__)
Output:
None
{'name': 'John', '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 this section of the tutorial, we will
discuss inheritance in detail.
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
1. class derived-class(base class):
2. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider
the following syntax.
Syntax
1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
2. <class - suite>
Example 1
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. d.bark()
10. d.speak()
Output:
dog barking
Animal Speaking
Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. d.bark()
14. d.speak()
15. d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Syntax
1. class Base1:
2. <class-suite>
3.
4. class Base2:
5. <class-suite>
6. .
7. .
8. .
9. class BaseN:
10. <class-suite>
11.
12. class Derived(Base1, Base2, ...... BaseN):
13. <class-suite>
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(d.Summation(10,20))
12. print(d.Multiplication(10,20))
13. print(d.Divide(10,20))
Output:
30
200
0.5
Output:
True
False
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(isinstance(d,Derived))
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.
Example
1. class Animal:
2. def speak(self):
3. print("speaking")
4. class Dog(Animal):
5. def speak(self):
6. print("Barking")
7. d = Dog()
8. d.speak()
Output:
Barking
Output:
Output: