0% found this document useful (0 votes)
3 views165 pages

Python Unit 1 2 3

The document provides an introduction to Python, detailing its features, history, and execution process. Developed by Guido Van Rossum in 1991, Python combines elements of C and Java, is open-source, and supports both procedural and object-oriented programming. It is platform-independent, dynamically typed, and has a large library, making it suitable for various applications including scripting and database connectivity.

Uploaded by

vasudevay97
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views165 pages

Python Unit 1 2 3

The document provides an introduction to Python, detailing its features, history, and execution process. Developed by Guido Van Rossum in 1991, Python combines elements of C and Java, is open-source, and supports both procedural and object-oriented programming. It is platform-independent, dynamically typed, and has a large library, making it suitable for various applications including scripting and database connectivity.

Uploaded by

vasudevay97
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION TO PYTHON

Dr. Himanshu Pant


Assistant Professor,
School of Computing
Graphic Era Hill University, Bhimtal
• Python is a programming language that combines the features of C and
Java.
• It offers elegant style of developing programs like C.
• When the programmers want to go for object orientation, Python offers
classes and objects like Java.
• Python was developed by Guido Van Rossum in the year 1991 at the Center
for Mathematics and Computer Science managed by the Dutch
Government.
• Van Rossum was working on a project to develop system utilities in C
where he had to interact with the Bourne shell available in UNIX.
• He felt the necessity of developing a language that would fill the gap
between C and the shell.
• Van Rossum picked the name Python for the new language from the
TV show, Monty Python’s Flying Circus.
• Python’s first working version was ready by early 1990 and Van
Rossum released it for the public on February 20, 1991.
• The logo of Python shows two intertwined snakes as shown in Figure
1.1:

• Python is open source software, which means anybody can freely


download it from www.python.org and use it to develop programs.
• Its source code can be accessed and modified as required in the
projects.
Features of Python
• Simple: Python is a simple programming language. When we read a Python
program, we feel like reading English sentences. It means more clarity and less
stress on understanding the syntax of the language. Hence, developing and
understanding programs will become easy.
• Easy to learn: Python uses very few keywords. Its programs use very simple
structure. So, developing programs in Python become easy. Also, Python
resembles C language. Most of the language constructs in C are also available in
Python. Hence, migrating from C to Python is easy for programmers.
• Open source: There is no need to pay for Python software. Python can be freely
downloaded from www.python.org website. Its source code can be read,
modified and can be used in programs as desired by the programmers.
 High level language: Programming languages are of two types: low level and high level. A low level language
uses machine code instructions to develop programs. These instructions directly interact with the CPU. Machine
language and assembly language are called low level languages. High level languages use English words to
develop programs. These are easy to learn and use. Like COBOL, PHP or Java, Python also uses English words in
its programs and hence it is called high level programming language.
 Dynamically typed: In Python, we need not declare anything. An assignment statement binds a name to an
object, and the object can be of any type. If a name is assigned to an object of one type, it may later be assigned
to an object of a different type. This is the meaning of the saying that Python is a dynamically typed language.
Languages like C and Java are statically typed. In these languages, the variable names and datatypes should
be mentioned properly. Attempting to assign an object of the wrong type to a variable name triggers error or
exception.
 Platform independent: When a Python program is compiled using a Python compiler, it generates byte code. Python’s
byte code represents a fixed set of instructions that run on all operating systems and hardware. Using a Python Virtual
Machine (PVM), anybody can run these byte code instructions on any computer system. Hence, Python programs are
not dependent on any specific operating system. We can use Python on almost all operating systems like UNIX, Linux,
Windows, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, etc. This makes Python an ideal programming language for
any network or Internet.
 Portable: When a program yields the same result on any computer in the world, then it is called a portable program.
Python programs will give the same result since they are platform independent. Once a Python program is written, it
can run on any computer system using PVM. However, Python also contains some system dependent modules (or
code), which are specific to operating system. Programmers should be careful about such code while developing the
software if they want it to be completely portable.
 Procedure and object oriented: Python is a procedure oriented as well as an object oriented programming language.
In procedure oriented programming languages (e.g. C and Pascal), the programs are built using functions and
procedures. But in object oriented languages (e.g. C++ and Java), the programs use classes and objects.
 Interpreted: A program code is called source code. After writing a Python program, we should compile the source
code using Python compiler. Python compiler translates the Python program into an intermediate code called byte
code. This byte code is then executed by PVM. Inside the PVM, an interpreter converts the byte code instructions into
machine code so that the processor will understand and run that machine code to produce results.
 Extensible: The programs or pieces of code written in C or C++ can be integrated into Python and executed using
PVM. This is what we see in standard Python that is downloaded from www.python.org. There are other flavors of
Python where programs from other languages can be integrated into Python. For example, Jython is useful to
integrate Java code into Python programs and run on JVM (Java Virtual Machine). Similarly, Iron Python is useful to
integrate .NET programs and libraries into Python programs and run on CLR (Common Language Runtime).
 Embeddable: We can insert Python programs into a C or C++ program. Several applications are already
developed in Python which can be integrated into other programming languages like C, C++, Delphi, PHP, Java
and .NET. It means programmers can use these applications for their advantage in various software projects.
 Huge library: Python has a big library which can be used on any operating system like UNIX, Windows or
Macintosh. Programmers can develop programs very easily using the modules available in the Python library.
 Scripting language: A scripting language is a programming language that does not use a compiler for
executing the source code. Rather, it uses an interpreter to translate the source code into machine code on the
fly (while running). Generally, scripting languages perform supporting tasks for a bigger application or software.
For example, PHP is a scripting language that performs supporting task of taking input from an HTML page
and send it to Web server software. Python is considered as a scripting language as it is interpreted and it is used
on the Internet to support other software.
 Database connectivity: A database represents software that stores and manipulates data. For example, Oracle is
a popular database using which we can store data in the form of tables and manipulate the data. Python provides
interfaces to connect its programs to all major databases like Oracle, Sybase or MySql.
 Scalable: A program would be scalable if it could be moved to another operating system or hardware and
take full advantage of the new environment in terms of performance. Python programs are scalable since they
can run on any platform and use the features of the new platform effectively.
Execution of a Python Program
• We write a Python program with the name x.py. Here, x is the program name and the .py is the
extension name. After typing the program, the next step is to compile the program using Python
compiler.
• The compiler converts the Python program into another code called byte code.
• Byte code represents a fixed set of instructions that represents all operations like arithmetic operations,
comparison operations, memory related operations, etc., which run on any operating system and
hardware.
• It means the byte instructions are system independent or platform independent.
• The size of each byte code instruction is 1 byte and hence they are called with the name byte code.
• These byte code instructions are contained in the file x.pyc. Here, the x.pyc file represents a python
compiled file.
• The next step is to run the program. If we directly give the byte code to the computer, it cannot execute
them.
• Any computer can execute only binary code which comprises 1s and 0s.
• It is therefore necessary to convert the byte code into machine code so that our computer can
understand and execute it. For this purpose, we should use PVM (Python Virtual Machine).
• PVM uses an interpreter which understands the byte code and converts it into machine code. PVM
first understands the processor and operating system in our computer. Then it converts the byte code
into machine code understandable to that processor and into that format understandable to that
operating system. These machine code instructions are then executed by the processor and results
are displayed.
• An interpreter translates the program source code line by line. Hence, it is slow.
• The interpreter that is found inside the PVM runs the Python program slowly.
• To rectify this problem, in some flavors of Python, a compiler is added to the PVM.
• This compiler also converts the byte code into machine code but faster than the interpreter.
• This compiler is called JIT (Just In Time) compiler. The advantage of JIT compiler is to improve speed of
execution of a Python program and thus improving the performance.
• Normally, when we compile a Python program, we cannot see the .pyc file produced by the Python
compiler and the machine code generated by the PVM. This is done internally in the memory and the
output is finally visible.
• For example, if our Python program name is x.py, we can use Python compiler to compile it as:

C:\>python x.py
• In the preceding statement, python is the command for calling the Python compiler. The compiler should convert
the x.py file into its byte code equivalent file, x.pyc. Instead of doing this, the compiler directly displays the
output or result.
• If we observe, we cannot find any files in the directory with the extension .pyc. The reason is that all the steps in
the sequence: source code  byte code  machine code output are internally completed and then the final
result is displayed. Hence, after execution, we cannot find any .pyc file in the directory.
• To separately create .pyc file from the source code, we can use the following command:

C:\>python –m py_compile x.py

• In the preceding command, we are calling the Python compiler with –m option. -m represents module and the
module name is py_compile. This module generates the .pyc file for the specified .py file. The compiler creates a
separate directory in the current directory by the name pycache where it stores the .pyc file. The .pyc file name
may be something like: x.cpython-34.pyc. The word cpython here indicates that we are using the Python compiler
that was created using C. This is of course, the standard Python compiler.
• So the question is ‘What is the use of the .pycfiles’? We know that the .pyc files contain byte code. We get
these files after the compilation is completed. Hence, the first step is over. The next step is to interpret
them using PVM. This can be done by calling the Python compiler as:

C:\>python x.cpython-34.pyc

• In this case, we are supplying .pyc file to the Python compiler. Now, Python compiler will skip the first step where it
has to convert the source code into byte code as already it sees the byte code inside this .pyc file. This file is
executed directly by the PVM to produce the output.
Viewing the Byte Code
• Let’s consider the following Python program:
# Python program to add two numbers
a = b = 10 # take two variables and store 10 in to them
print("Sum= ", (a+b)) # display their sum
• We can type this program in a text editor like Notepad and then save
it as ‘first.py’. It means, the first.py file contains the source code.
• Now, let’s compile the program using Python compiler as:
C:\>python first.py
• It will display the result as: Sum= 20
• That is ok. But we do not want the output of the program. We want to see the byte code instructions that were
created internally by the Python compiler before they are executed by the PVM. For this purpose, we should
specify the dis module while using python command as:
C:\>python –m dis first.py
It will produce the following output:
• The preceding byte code is displayed by the dis module, which is also known as 'disassembler' that displays the
byte code in the human understandable format.
• If we observe the preceding code, we can find 5 columns.
• The left-most or first column represents the line number in our source program (first.py).
• The second column represents the offset position of the byte code.
• The third column shows the name of the byte code instruction.
• The 4th column represents instruction's argument.
• The last column represents constants or names as specified by 4th column. For example, see the following
instructions:

• The LOAD_NAME specifies that this byte code instruction has 2 arguments. The name that has 2 arguments
is (print) function. Since there are 2 arguments, the next byte code instructions will represent those 2
arguments as LOAD_CONST represents the string constant name ('Sum= ') and (a) and (b) as names involved
in the second argument for the print function. Then BINARY_ADD instruction adds the previous (i.e. a and b)
values.
Flavors of Python
• Flavors of Python refer to the different types of Python compilers. These flavors are useful to
integrate various programming languages into Python.
• CPython: This is the standard Python compiler implemented in C language. This is the Python
software being downloaded and used by programmers directly from
https://www.python.org/downloads/. In this, any Python program is internally converted into
byte code using C language functions. This byte code is run on the interpreter available in Python
Virtual Machine (PVM) created in C language. The advantage is that it is possible to execute C
and C++ functions and programs in CPython.
• Jython: This is earlier known as JPython. This is the implementation of Python programming
language which is designed to run on Java platform. Jython compiler first compiles the Python
program into Java byte code. This byte code is executed by Java Virtual Machine (JVM) to
produce the output. Jython contains libraries which are useful for both Python and Java
programmers. This can be downloaded from http://www.jython.org/.
 IronPython: This is another implementation of Python language for .NET framework. This is written in C#
(C Sharp) language. The Python program when compiled gives an intermediate language (IL) which runs
on Common Language Runtime (CLR) to produce the output. This flavor of Python gives flexibility of using
both the .NET and Python libraries. IronPython can be downloaded from http://ironpython.net/.
 RubyPython: This is a bridge between the Ruby and Python interpreters. It encloses a Python interpreter
inside Ruby applications. This flavor of Python can be downloaded from
https://rubygems.org/gems/rubypython/versions/0.6.3.
 Pythonxy: This is pronounced as Python xy and written as Python(X,Y). This is the Python implementation that
we get after adding scientific and engineering related packages. We can download Pythonxy from
https://python-xy.github.io/downloads.html.
 AnacondaPython: When Python is redeveloped for handling large-scale data processing, predictive analytics
and scientific computing, it is called Anaconda Python. This implementation mainly focuses on large scale of
data. This can be downloaded from https://www.continuum.io/downloads.
Frozen Binaries
• When a software is developed in Python, there are two ways to provide the software to the
end user. The first way is to provide the .pyc files to the user. The user will install PVM in his
computer and run the byte code instructions of the .pyc files.
• The other way is to provide the .pyc files, PVM along with necessary Python library. In this
method, all the .pyc files, related Python library and PVM will be converted into a single
executable file (generally with .exe extension) so that the user can directly execute that file
by double clicking on it.
• In this way, converting the Python programs into true executables is called frozen binaries.
But frozen binaries will have more size than that of simple .pyc files since they contain PVM
and library files also.
• For creating frozen binaries, we need to use other party software. For example, py2exe is a
software that produces frozen binaries for Windows operating system. We can use
pyinstaller for UNIX or LINUX. Freeze is another program from Python organization to
generate frozen binaries for UNIX.
Memory Management in Python
• In C or C++, the programmer should allocate and deallocate (or free) memory dynamically,
during runtime. For example, to allocate memory, the programmer may use malloc() function
and to deallocate the memory, he may use the free() function.
• But in Python, memory allocation and deallocation are done during runtime automatically.
The programmer need not allocate memory while creating objects or deallocate memory
when deleting the objects. Python’s PVM will take care of such issues.
• Everything is considered as an object in Python. For example, strings are objects. Lists are
objects. Functions are objects. Even modules are also objects. For every object, memory
should be allocated. Memory manager inside the PVM allocates memory required for objects
created in a Python program. All these objects are stored on a separate memory called heap.
• Heap is the memory which is allocated during runtime.
Garbage Collection in Python
• Garbage collector is a module in Python that is useful to delete objects from
memory which are not used in the program.
• The module that represents the garbage collector is named as gc.
• Garbage collector in the simplest way to maintain a count for each object
regarding how many times that object is referenced (or used).
• When an object is referenced twice, its reference count will be 2. When an object
has some count, it is being used in the program and hence garbage collector will
not remove it from memory.
• When an object is found with a reference count 0, garbage collector will
understand that the object is not used by the program and hence it can be
deleted from memory.
• Hence, the memory allocated for that object is deallocated or freed.
Comparisons between C and Python
C Python
The programmer should allocate and deallocate Memory allocation and deallocation is done
memory using malloc(), calloc(), realloc() or free() automatically by PVM.
functions.
C does not contain a garbage collector. Automatic garbage collector is available in Python.

C supports single and multi-dimensional arrays. Python supports only single dimensional arrays. To work
with multi-dimensional arrays, we should use third
party applications like numpy.
The array index should be positive integer. Array index can be positive or negative integer number.
Negative index represents locations from the end of the
array.
Checking the location outside the allocation of an array Python performs checking outside an array for all
is not supported in C. iterations while looping.
Indentation of statements is not necessary in C. Indentation is required to represent a block of
statements.
A semicolon is used to terminate the statements in C New line indicates end of the statements and semicolon
and comma is used to separate expressions. is used as an expression separator.
C supports in-line assignments. Pythondoes not support in-line assignments.
Comparisons between Java and Python
Java Python
Java is object-oriented programming language. Functional programming features are Python blends the functional programming with object-oriented programming
introduced into Java 8.0 through lambda expressions features. Lambdas are already available in Python.
It is compulsory to declare the datatypes of variables, arrays etc. in Java. Type declaration is not required in Python.

Java language type discipline is static and weak. Python type discipline is dynamic and strong.

Java has do… while, while, for and for each loops. Python has while and for loops.

Java has switch statement. Python does not have switch statement.

The variable in for loop does not increment automatically. But in for each loop, it will The variable in the for loop increments automatically.
increment automatically.
Memory allocation and deal location is done automatically by JVM (Java Virtual Memory allocation and deal location is done automatically by PVM (Python Virtual
Machine). Machine).
Java supports single and multi-dimensional arrays. Python supports only single dimensional arrays. To work with multi-dimensional
arrays, we should use third party applications like numpy.
The array index should be a positive integer. Array index can be positive or negative integer number. Negative index represents
locations from the end of the array.
Checking the location outside the allocation of an array is not supported in Java. Python performs checking outside an array for all iterations while looping.

Indentation of statements is not necessary in Java. Indentation is required to represent a block of statements.
A semicolon is used to terminate the statements and comma is used to separate New line indicates end of the statements and semicolon is used as an expression
expressions. separator.
Points to Remember
• Python was developed by Guido Van Rossum in the year 1991.
• Python is a high level programming language that contains features of functional programming language like
C and object oriented programming language like Java.
• The standard Python compiler is written in C language and hence called CPython.
• There are other flavors of Python, namely Jython, IronPython and PyPy.
• A Python program contains source code that is first compiled by Python compiler to produce byte code. This
byte code is given to Python Virtual Machine (PVM) which converts the byte code to machine code so that
the processor will execute it and display the results.
• Python’s byte code is a set of instructions created by the Python development team to represent all type of
operations. Each byte code occupies 1 byte of memory and hence the name byte code.
• Python Virtual Machine (PVM) is the software containing an interpreter that converts the byte code into
machine code depending on the operating system and hardware of the computer system where the Python
program runs.
• The standard PVM contains only an interpreter and hence Python is called an interpreted language.
• PVM is most often called Python interpreter.
• The PVM of PyPy contains a compiler in addition to the interpreter. This compiler is called Just In Time (JIT)
compiler which is useful to speed up the execution of the Python program.
• The programmer need not allocate or deallocate memory in Python. It is the duty of the PVM to allocate or
deallocate memory for Python programs.
• Memory manager is a module (or sub program) in PVM which will
allocate memory for objects. Garbage collector is another module in
PVM that will deallocate (or free) memory for the unused objects.
• The programmer need not call the garbage collector. It will execute
automatically when the Python program is running in memory. In
addition, the programmer can also call the garbage collector whenever
needed.
• The files that contain Python programs along with Python compiler and
libraries that can be executed directly are called frozen binaries.
• The ‘py_compile’ module converts a Python source file into a .pyc file
that contains byte code instructions. Generally, the .pyc files are
provided to the end user.
• When the Python source file is given, the ‘dis’ module displays the
equivalent byte code instructions in human readable format.
Installing Python for Windows
Download Python
• Go to the official Python website: https://www.python.org/downloads/windows/
• Download the latest stable release (e.g., Python 3.x.x).
• Choose the Windows Installer (64-bit) if your system is 64-bit (most common).

Run the Installer


•Locate the downloaded file.
•Important: On the first screen, check ✅ "Add Python 3.x to PATH" at the bottom.
•This allows you to use Python from Command Prompt.
•Click "Install Now" (recommended).

Verify Installation
• Open Command Prompt (Win + R, type cmd, press Enter).
• Type:
python --version
Installing python in ubuntu
• Update Package List
sudo apt update
• Check Existing Python Version
python3 --version
• Install Python
sudo apt install python3 -y
• Install PIP (Python Package Manager)
sudo apt install python3-pip -y
• Verify Installation
python3 --version
pip3 --version
Installing numpy
• Python supports only single dimensional arrays. To create multi-
dimensional arrays, we need a special package called Numerical
Python package or numpy. To download and install this package, first
we should go to System prompt and then use ‘pip’ (Python
Installation of Packages) command as shown below:
C:\> pip install numpy
Installing pandas
• pandas is a package used in data analysis. This package is mostly used
by data scientists and data analysts. To download and install this
package, we should go to System prompt and then use ‘pip’ (Python
Installation of Packages) command as shown below:
C:\> pip install pandas
Installing xlrd
• xlrd is a package that is useful to retrieve data from Microsoft Excel
spreadsheet files. Hence, it is useful in data analysis. To download and
install this package, we should go to System prompt and then use
‘pip’ (Python Installation of Packages) command as shown below:
C:\> pip install xlrd
Installing matplotlib
• matplotlib is another important package in Python that is useful to produce good
quality 2D graphics. It is mostly used for the purpose of showing data in the form
of graphs and also for designing electronic circuits, machinery parts, etc. To
download and install this package, we should go to System prompt and then use
‘pip’ (Python Installation of Packages) command as shown below:
C:\> pip install matplotlib
Verifying Installed Packages
• We can verify whether the installed packages are added to our
Python software properly or not by going into Python and typing the
following command at Python prompt (triple greater than symbol) as:
>>> help(‘modules’)
Writing Our First Python Program
# first program to add two numbers – line 1
a = 10 # store 10 into variable a – line 2
b = 15 # store 15 into variable b – line 3
c=a+b # add 10 and 15 and store into variable c – line 4
print("Sum= ", c) # display the sum – line 5

• The hash symbol ‘#’ represents the comment line in Python.


• Comments are not executed by the Python compiler or PVM.
• Hence, it is not compulsory to write comments; however, comments
improve understanding of a program.
Executing a Python Program
• There are three ways of executing a Python program.
Using Python’s command line window
Using Python’s IDLE graphics window
Directly from System prompt
• The first two are called interactive modes where we can type the
program one line at a time and the PVM executes it immediately.
• The last one is called non-interactive mode where we ask the PVM to
execute our program after typing the entire program.
Using Python’s Command Line Window
• Click the Python’s command line icon which is already added to our
taskbar.
• This will open Python’s command line window. We can see >>>
symbol which is called Python prompt.

• After typing the last line and pressing the Enter button, we can see
the result of our program.
• After that, type exit() or quit() at the Python prompt. This will
terminate the PVM and close the window.
Using Python’s IDLE Graphics Window
• It is possible to execute a Python program by going to Integrated
Development Environment (IDLE) which provides graphical interface
to the user.
• Click the Python’s IDLE icon. This will open the Python’s IDLE window.

• To terminate the IDLE window, type exit() or quit() at the Python


prompt. It will display a message as to kill the program or not.
• Click the ‘OK’ button. The Python compiler will terminate and the
window will close.
Running Directly from System Prompt
• In most programming environments like Java or .NET, we can generally type
the program in a Text editor like Notepad or EditPlus.
• After typing the entire program, we save it and then call the compiler to
compile the program. This can be done in Python also.
1. Open a text editor and type the program
2. Save the program by clicking File à Save As. Type the program name as "first.py“.
3. Open the command prompt (or DOS prompt) window and go to that directory where
the program is saved. This can be done by typing COMMAND or CMD commands at
Start à Run.
4. Now execute the first.py program by calling the python command. For this purpose,
type python along with the file name at the command prompt window as:
F:\PY>python first.py

5. To close the command prompt window, we can type exit as:


F:\PY>exit
Comments in Python
• There are two types of comments in Python:
single line comments
 multi line comments
• Single line comments
These comments start with a hash symbol ( # ) and are useful to
mention that the entire line till the end should be treated as comment.
• Multi line comments
• When we want to mark several lines as comment, then writing # symbol in
the beginning of every line will be a tedious job.
• Instead of starting every line with # symbol, we can write the previous
block of code inside """ (triple double quotes) or ''' (triple single quotes) in
the beginning and ending of the block as:
Docstrings
• In fact, Python supports only single line comments.
• Multi line comments are not available in Python.
• The triple double quotes or triple single quotes are actually not multi line
comments but they are regular strings with the exception that they can
span multiple lines.
• That means memory will be allocated to these strings internally.
• If these strings are not assigned to any variable, then they are removed
from memory by the garbage collector and hence these can be used as
comments.
• If we write strings inside """ or ''' and if these strings are written as first
statements in a module, function, class or a method, then these strings are
called documentation strings or docstrings.
Datatypes in Python
• A datatype represents the type of data stored into a variable or
memory.
• The datatypes which are already available in Python language are
called Built-in datatypes.
• The datatypes which can be created by the programmers are called
User-defined datatypes.
Built-in datatypes
• The built-in datatypes are of Six types:
None Type
Numeric types
Bool
Sequences
Sets
Mappings
The None Type
• In Python, the ‘None’ datatype represents an object that does not contain
any value.
• In languages like Java, it is called ‘null’ object. But in Python, it is called
‘None’ object.
• In a Python program, maximum of only one ‘None’ object is provided.
• One of the uses of ‘None’ is that it is used inside a function as a default
value of the arguments.
• When calling the function, if no value is passed, then the default value will
be taken as ‘None’. If some value is passed to the function, then that value
is used by the function. In Boolean expressions, ‘None’ datatype represents
‘False’.
Numeric Types
• The numeric types represent numbers. There are three sub types:
int
float
complex
• int Datatype
The int datatype represents an integer number. An integer number is a number
without any decimal point or fraction part. In Python, there is no limit for the size of an
int datatype. It can store very large integer numbers conveniently.
• float Datatype
The float datatype represents floating point numbers. A floating point number is
a number that contains a decimal point.
• Complex Datatype
A complex number is a number that is written in the form of a + bj or a + bJ.
Here, ‘a’ represents the real part of the number and ‘b’ represents the imaginary part of
the number.
Representing Binary, Octal and Hexadecimal
Numbers
• A binary number should be written by prefixing 0b (zero and b) or 0B (zero
and B) before the value. For example, 0b110110, 0B101010011 are
treated as binary numbers.
• Hexadecimal numbers are written by prefixing 0x (zero and x) or 0X (zero
and big X) before the value, as 0xA180 or 0X11fb91 etc.
• Similarly, octal numbers are indicated by prefixing 0o (zero and small o) or
0O (zero and then O) before the actual value. For example, 0O145 or
0o773 are octal values.
Converting the Datatypes Explicitly
• Depending on the type of data, Python internally assumes the datatype for the variable.
• But sometimes, the programmer wants to convert one datatype into another type on his own.
• This is called type conversion or coercion. This is possible by mentioning the datatype with parentheses.
 int(x) is used to convert the number x into int type.
x = 15.56
int(x) # will display 15
 float(x) is used to convert x into float type.
num = 15
float(num) # will display 15.0
 complex(x) is used to convert x into a complex number with real part x and imaginary part zero.
n = 10
complex(n) # will display (10+0j)
 complex(x, y) is used to convert x and y into a complex number such that x will be the real part and y will be
the imaginary part.
a = 10
b = -5
complex(a, b) # will display (10-5j)
# python program to convert into decimal number
system
n1 = 0O17
n2 = 0B1110010
n3 = 0X1c2
n = int(n1)
print('Octal 17 = ', n)
n = int(n2)
print('Binary 1110010 = ', n)
n = int(n3)
print('Hexadecimal 1c2 = ', n)

Output:
C:\>python convert.py
Octal 17 = 15
Binary 1110010 = 114
Hexadecimal 1c2 = 450
• There is a function in the form of int (string, base) that is useful to convert a string into
a decimal integer. ‘string’ represents the string format of the number. It should contain
integer number in string format. ‘base’ represents the base of the number system to
be used for the string.
# python program to convert into decimal number
s1 = "17"
s2 = "1110010“
s3 = "1c2"
n = int(s1, 8)
print('Octal 17 = ', n)
n = int(s2, 2)
print('Binary 1110010 = ', n)
n = int(s3, 16)
print('Hexadecimal 1c2 = ', n)

Output:
C:\>python convert.py
Octal 17 = 15
Binary 1110010 = 114
Hexadecimal 1c2 = 450
• We can also use functions bin() for converting a number into binary
number system.
• The function oct() will convert a number into octal number system
• The function hex() will convert a number into hexadecimal number system.

a = 10
b = bin(a)
print(b) # displays 0b1010

b = oct(a)
print(b) # displays 0o12

b = hex(a)
print(b) # displays 0xa
bool Datatype
• The bool datatype in Python represents boolean values.
• There are only two boolean values True or False that can be represented by this
datatype.
• Python internally represents True as 1 and False as 0.
• A blank string like "" is also represented as False.
• Conditions will be evaluated internally to either True or False.
a = 10
b = 20
if(a<b): print("Hello") # displays Hello.

In this code, the condition a<b which is written after if - is evaluated to True and hence it will
execute print("Hello").
a = 10>5 # here ‘a’ is treated as bool type variable
print(a) # displays True

a = 5>10
print(a) # displays False
Sequences in Python

• Generally, a sequence represents a group of elements or items.


• For example, a group of integer numbers will form a sequence.
• There are six types of sequences in Python:
str
bytes
bytearray
list
tuple
range
str Datatype
• In Python, str represents string datatype.
• A string is represented by a group of characters.
• Strings are enclosed in single quotes or double quotes. Both are valid.
Str = “Welcome” # here str is name of string type variable
str = ‘Welcome’ # here str is name of string type variable
• We can also write strings inside """ (triple double quotes) or ''' (triple single quotes) to span a group of lines
including spaces.
str1 = """This is a book on Python which discusses all the topics of Core Python in a easy manner
with examples."""
str2 = '''This is a book on Python which discusses all the topics of Core Python in a easy manner with
examples.'''
• The triple double quotes or triple single quotes are useful to embed a string inside another string as shown
below:
str = """This is 'Core Python' book."""
print(str) # will display: This is 'Core Python' book.

str = '''This is "Core Python" book.'''


print(str) # will display: This is "Core Python" book.
• The slice operator represents square brackets [ ] to retrieve pieces of a string.
• For example, the characters in a string are counted from 0 onwards.
• Hence, str[0] indicates the 0th character or beginning character in the string.
s = 'Welcome to Core Python' # this is the original string
print(s)
Output:
Welcome to Core Python

print(s[0]) # display 0th character from s W


print(s[3:7]) # display from 3rd to 6th characters come

print(s[11:]) # display from 11th characters onwards till end Core Python

print(s[-1]) # display first character from the end n


The repetition operator is denoted by ‘*’ symbol and useful to repeat the string for several
times. For example s * n repeats the string for n times.
print(s*2)
Output: Welcome to Core PythonWelcome to Core Python
bytes Datatype
• The bytes datatype represents a group of byte numbers just like an array
does.
• A byte number is any positive integer from 0 to 255 (inclusive).
• bytes array can store numbers in the range from 0 to 255 and it cannot
even store negative numbers.
elements = [10, 20, 0, 40, 15] # this is a list of byte numbers
x = bytes(elements) # convert the list into bytes array
print(x[0]) # display 0th element, i.e 10
We cannot modify or edit any element in the bytes type array.
• For example, x[0] = 55 gives an error. Here we are trying to replace 0th
element (i.e. 10) by 55 which is not allowed.
• write a Python program to create a bytes type array with a group of
elements and then display the elements using a for loop. In this program,
we are using a for loop as:
for i in x: print(i)
It means, if ‘i’ is found in the array ‘x’ then display i value using print()
function.
Remember, we need not declare the datatypes of variables in Python.
Hence, we need not tell which type of variable ‘i’ is. In the above loop, ‘i’
stores each element of the array ‘x’ and with every element, print(i) will
be executed once. Hence, print(i) displays all elements of the array ‘x’.
# program to understand bytes type array
# create a list of byte numbers
elements = [10, 20, 0, 40, 15]
# convert the list into bytes type array
x = bytes(elements)
# retrieve elements from x using for loop and display
for i in x: print(i)

Output:
C:\>python bytes.py
10
20
0
40
15
bytearray Datatype
• The bytearray datatype is similar to bytes datatype.
• The difference is that the bytes type array cannot be modified but the bytearray type array can be modified.
• It means any element or all the elements of the bytearray type can be modified.
• To create a bytearray type array, we can use the function bytearray.
# create a list of byte numbers
elements = [10, 20, 0, 40, 15]
# convert the list into bytearray type array
x = bytearray(elements)
# modify the first two elements of x
x[0] = 88
x[1] = 99
# retrieve elements from x using for loop and display
for i in x: print(i)
Output:
C:\>python bytearray.py
88
99
0
40
15
list Datatype
• Lists in Python are similar to arrays in C or Java.
• A list represents a group of elements.
• The main difference between a list and an array is that a list can store
different types of elements but an array can store only one type of
elements.
• Also, lists can grow dynamically in memory. But the size of arrays is
fixed and they cannot grow at runtime.
• Lists are represented using square brackets [ ] and the elements are
written in [ ], separated by commas.
list = [10, -20, 15.5, 'Vijay', "Mary"]
• The slicing operation like [0: 3] represents elements from 0th to 2nd
positions, i.e. 10, 20, 15.5.
tuple Datatype
• A tuple is similar to a list.
• A tuple contains a group of elements which can be of different types.
• The elements in the tuple are separated by commas and enclosed in parentheses
( ).
• Whereas the list elements can be modified, it is not possible to modify the tuple
elements.
• That means a tuple can be treated as a read-only list.
tpl = (10, -20, 15.5, 'Vijay', "Mary")
• The individual elements of the tuple can be referenced using square braces as
tpl[0], tpl[1], tpl[2], … Now, if we try to modify the 0th element as:
tpl[0] = 99
• This will result in error.
• The slicing operations which can be done on lists are also valid in tuples.
range Datatype
• The range datatype represents a sequence of numbers.
• The numbers in the range are not modifiable.
• Generally, range is used for repeating a for loop for a specific number of times.
r = range(10)
• Here, the range object is created with the numbers starting from 0 to 9. We can
display these numbers using a for loop as:
for i in r: print(i) #display numbers from 0 to 9.
• We can use a starting number, an ending number and a step value in the range
object as:
r = range(30, 40, 2)
• This will create a range object with a starting number 30 and an ending number
39. The step size is 2. It means the numbers in the range will increase by 2 every
time.
for i in r: print(i) #display numbers: 30, 32, 34, 36, 38
Sets
• A set is an unordered collection of elements much like a set in
Mathematics.
• The order of elements is not maintained in the sets.
• It means the elements may not appear in the same order as they are
entered into the set.
• Moreover, a set does not accept duplicate elements.
• There are two sub types in sets:
set datatype
frozenset datatype
set Datatype
• To create a set, we should enter the elements separated by commas inside
curly braces { }.
s = {10, 20, 30, 20, 50}
print(s) # may display {50, 10, 20, 30}
Observe that the set ‘s’ is not maintaining the order of the elements. We
entered the elements in the order 10, 20, 30, 20 and 50. But it is showing
another order. Also, we repeated the element 20 in the set, but it has stored
only one 20.
ch = set("Hello")
print(ch) # may display {'H', 'e', 'l', 'o'}
Here, a set ‘ch’ is created with the characters H,e,l,o. Since a set does not
store duplicate elements, it will not store the second ‘l’.
• We can convert a list into a set using the set() function as:
lst = [1,2,5,4,3]
s = set(lst)
print(s) # may display {1, 2, 3, 4, 5}
• Since sets are unordered, we cannot retrieve the elements using indexing or
slicing operations. For example, the following statements will give error
messages:
print(s[0]) # indexing, display 0th element
print(s[0:2]) # slicing, display from 0 to 1st elements
The update() method is used to add elements to a set as:
s.update([50,60])
print(s) # may display {1, 2, 3, 4, 5, 50, 60}
remove() method is used to remove any particular element from a set as:
s.remove(50)
print(s) # may display {1, 2, 3, 4, 5, 60}
frozenset Datatype
• The frozenset datatype is same as the set datatype.
• The main difference is that the elements in the set datatype can be modified;
whereas, the elements of frozenset cannot be modified.
• We can create a frozenset by passing a set to frozenset() function.
s = {50,60,70,80,90}
print(s) # may display {80, 90, 50, 60, 70}
fs = frozenset(s) # create frozenset fs
print(fs) # may display frozenset({80, 90, 50, 60, 70})
• Another way of creating a frozenset is by passing a string (a group of characters)
to the frozenset().
fs = frozenset("abcdefg")
print(fs) # may display frozenset({'e', 'g', 'f', 'd', 'a', 'c', 'b'})
update() and remove() methods will not work on frozensets since they cannot
be modified or updated.
Mapping Types
• A map represents a group of elements in the form of key value pairs so that when the
key is given, we can retrieve the value associated with it.
• The dict datatype is an example for a map.
• The ‘dict’ represents a ‘dictionary’ that contains pairs of elements such that the first
element represents the key and the next one becomes its value.
• The key and its value should be separated by a colon ( : ) and every pair should be
separated by a comma.
• All the elements should be enclosed inside curly brackets { }.
• We can create a dictionary by typing the roll numbers and names of students. Here,
roll numbers are keys and names will become values. We write these key value pairs
inside curly braces as:
d = {10: 'Kamal', 11: 'Pranav', 12: 'Hasini', 13: 'Anup', 14: 'Reethu'}
• Here, d is the name of the dictionary. 10 is the key and its associated value is ‘Kamal’.
The next key is 11 and its value is ‘Pranav’. Similarly 12 is the key and ‘Hasini’ is it value.
13 is the key and ‘Anup’ is the value and 14 is the key and ‘Reethu’ is the value.
• We can create an empty dictionary without any elements as:
d = {}
• Later, we can store the key and values into d as:
d[10] = 'Kamal'
d[11] = 'Pranav'
• In the preceding statements, 10 represents the key and ‘Kamal’ is its value.
Similarly, 11 represents the key and its value is ‘Pranav’. Now, if we write
print(d)
It will display the dictionary as:
{10: 'Kamal', 11: 'Pranav'}
Literals in Python
• A literal is a constant value that is stored into a variable in a program.
a = 15
Here, ‘a’ is the variable into which the constant value ‘15’ is stored.
Hence, the value 15 is called ‘literal’. Since 15 indicates integer value, it
is called ‘integer literal’.
• The following are different types of literals in Python:
Numeric literals
Boolean literals
String literals
Numeric Literals
• These literals represent numbers.
Examples Literal name
450, -15 Integer literal
3.14286, -10.6, 1.25E4 Float literal
0x5A1C Hexadecimal literal
0557 Octal literal
0B110101 Binary literal
18+3J Complex literal

Boolean Literals
• Boolean literals are the True or False values stored into a bool type
variable.
String Literals
• A group of characters is called a string literal.
• These string literals are enclosed in single quotes ( ' ) or double quotes ( " ) or triple
quotes (''' or """).
• In Python, there is no difference between single quoted strings and double quoted
strings.
• Single or double quoted strings should end in the same line as:
s1 = 'This is first Indian book'
s2 = "Core Python"
• When a string literal extends beyond a single line, we should go for triple quotes.
s1 = '''This is first Indian book on Core Python exploring all important
and useful features'''
s2 = """This is first Indian book on Core Python exploring all important
and useful features"""
• In the preceding examples, the strings have taken up to 3 lines.
Hence, we inserted them inside triple single quotes (''') or triple
double quotes (""").
• When a string spans more than one line adding backslash ( \ ) will join
the next string to it.
str = "This is first line and \
this will be continued with the first line“
print(str)
Output: This is first line and this will be continued with the first line
• We can use escape characters like \n inside a string literal.
• When a \n is written, it will throw the cursor to the new line.
str = "This is \nPython"
print(str)
Output: This is
Python
Important Escape Characters in Strings
Escape character Meaning
\ New line continuation

\\ Display a single \

\’ Display a single quote

\” Display a double quote

\b backspace

\r Enter

\t Horizontal tab space

\v Vertical tab

\n New line
Determining the Datatype of a Variable
• To know the datatype of a variable or object, we can use the type() function.
• For example, type(a) displays the datatype of the variable ‘a’.
a = 15
print(type(a))
<class 'int'>
• Since we are storing an integer number 15 into variable ‘a’, the type of ‘a’ is assumed
by the Python interpreter as ‘int’.
• Observe the last line. It shows class ‘int’. It means the variable ‘a’ is an object of the
class ‘int’.
• It means ‘int’ is treated as a class.
• Every datatype is treated as an object internally by Python.
• In fact, every datatype, function, method, class, module, lists, sets, etc. are all objects
in Python.
What about Characters
• Languages like C and Java contain char datatype that represents a single character.
• Python does not have a char datatype to represent individual characters.
• It has str datatype which represents strings.
• We know a string is composed of several characters.
• Hence, when we think of a character, we should think of it as an element in a string.
• In the following statements, we are assigning a single character ‘A’ to a variable ‘ch’.
Then we find out the type of the ‘ch’ variable using the type() function.
ch = 'A'
print(type(ch))
<class 'str'>
• See that the type of ‘ch’ is displayed as ‘str’ type.
• So, there is no concept like char datatype in Python.
• To work with strings, we have to access the individual characters of a string using
index or position number.
• Suppose there is a string str where we stored a string literal ‘Bharat’ as:
str = 'Bharat'
print(str[0])
Output- B
• In the preceding example, the str[0] represents the 0th character, i.e. ‘B’.
Similarly, str[1] represents ‘h’ and str[2] represents ‘a’ and so on.
• To retrieve all the characters using a for loop, we can write:
for i in str: print(i)
and it will display the characters as:
B
h
a
r
t
• isupper() is a method that tests whether a string is uppercase or
lowercase.
• It returns True if the string is uppercase otherwise False.
• This method can be used on a character to know whether it is
uppercase letter or not. Let’s check the case of first two letters in
‘Bharat’ as:
str[0].isupper() # checking if ‘B’ is capital letter or not
True

str[1].isupper() # checking if ‘h’ is capital letter or not


False
Reserved words
• Reserved words are the words that are already reserved for some
particular purpose in the Python language.
• The names of these reserved words should not be used as identifiers.
• The following are the reserved words available in Python:
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async',
'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Identifiers
• An identifier is a name that is given to a variable or function or class etc.
• Identifiers can include letters, numbers, and the underscore character ( _ ).
• They should always start with a nonnumeric character.
• Special symbols such as ?, #, $, %, and @ are not allowed in identifiers.
• Some examples for identifiers are salary, name11, gross_income, etc.
• We should also remember that Python is a case sensitive programming
language. It means capital letters and small letters are identified separately by
Python.
• For example, the names ‘num’ and ‘Num’ are treated as different names and
hence represent different variables.
Naming Conventions in Python
• Python developers made some suggestions to the programmers regarding how to write
names in the programs.
• The rules related to writing names of packages, modules, classes, variables, etc. are
called naming conventions.
• The following naming conventions should be followed:
Packages: Package names should be written in all lower case letters. When multiple
words are used for a name, we should separate them using an underscore ( _ ).
Modules: Modules names should be written in all lower case letters. When multiple
words are used for a name, we should separate them using an underscore ( _ ).
Classes: Each word of a class name should start with a capital letter. This rule is
applicable for the classes created by us. Python’s built-in class names use all lowercase
words. When a class represents exception, then its name should end with a word ‘Error’.
Global variables or Module-level variables: Global variables names should be all
lower case letters. When multiple words are used for a name, we should separate
them using an underscore ( _ ).
Instance variables: Instance variables names should be all lower case letters. When
multiple words are used for a name, we should separate them using an underscore ( _
). Non-public instance variable name should begin with an underscore.
Functions: Function names should be all lower case letters. When multiple words are
used for a name, we should separate them using an underscore ( _ ).
Methods: Method names should be all lower case letters. When multiple words are
used for a name, we should separate them using an underscore ( _ ).
Method arguments: In case of instance methods, their first argument name should
be ‘self’. In case of class methods, their first argument name should be ‘cls’.
Constants: Constants names should be written in all capital letters. If a constant has
several words, then each word should be separated by an underscore ( _ ).
Non accessible entities: Some variables, functions and methods are not accessible
outside and they should be used as they are in the program. Such entities names are
written with double underscores before and double underscores after. For example,
_ init (self) is a function used in a class to initialize variables.
Points to Remember
 A variable represents a memory location where some data can be stored.
 Python has only single line comments starting with a hash symbol (#).
 Triple single quotes (''') or triple doubles quotes (""") can be used to create multi line comments.
 Docstrings are the strings written inside triple single quotes or triple double quotes and as first
statements in a function, class or a method. These docstrings are useful to create API documentation
file that contains the description of all features of a program or software.
 A datatype represents the type of data stored into a variable. The data stored into the variable is called
literal.
 There are four built-in datatypes in Python. They are numeric types, sequences, sets and mappings.
 A binary literal is represented using 0b or 0B in the beginning of a number.
 An octal literal is represented using 0o or 0O in the beginning of a number.
 If a number starts with 0x or 0X, then it is considered as a hexadecimal number.
 The ‘bool’ datatype represents either True or False. True is represented by 1 and False is represented by
0.
 A string literal can be enclosed in single quotes or double quotes. When a string spans more than single
line, then we need to enclose it inside triple single quotes (''') or triple double quotes (""").
 A list is a dynamically growing array that can store different types of elements. Lists are written using
square brackets [ ].
 A tuple is similar to a list but its elements cannot be modified. A tuple uses parentheses ( ) to enclose
its elements.
 The ‘range’ datatype represents sequence of numbers and is generally used to repeat
 a for loop.
 A set is an unordered collection of elements. A set uses curly braces { } to enclose its elements.
 A frozenset is similar to a set but its elements cannot be modified.
 A ’dict’ datatype represents a group of elements written in the form of several key- value pairs such
that when the key is given, its corresponding value can be obtained.
 We can use the type() function to determine the datatype of a variable.
 Python does not have a datatype to represent single character.
 A constant represents a fixed value that cannot be changed. Defining constants is not possible in
Python.
 An identifier is a name that is given to a variable, function, class, etc.
 The rules related to writing names for packages, modules, classes, functions, variables, etc., are called
naming conventions.
OPERATORS IN PYTHON
• An operator is a symbol that performs an operation.
• An operator acts on some variables called operands.
• If an operator acts on a single variable, it is called unary operator.
• If an operator acts on two variables, it is called binary operator.
• If an operator acts on three variables, then it is called ternary operator.
• We can classify the operators depending upon their nature, as shown below:
Arithmetic operators
Assignment operators
Unary minus operator
Relational operators
Logical operators
Boolean operators
Bitwise operators
Membership operators
Identity operators
Arithmetic Operators
• These operators are used to perform basic arithmetic operations.
• There are seven arithmetic operators available in Python.
• Since these operators act on two operands, they are called ‘binary operators’.
• Let’s assume a = 13 and b = 5 and see the effect of various arithmetic operators:
Operator Meaning Example Result
+ Addition operator. Adds two values. a+b 18
- Subtraction operator. Subtracts one value from another. a-b 8
* Multiplication operator. Multiplies values on either side of the a*b 65
operator.
/ Division operator. Divides left operand by the right operand. a/b 2.6

% Modulus operator. Gives remainder of division. a%b 3


** Exponent operator. Calculates exponential power value. a ** b a**b 371293
gives the value of a to the power of b.
// Integer division. This is also called Floor division. Performs a//b 2
division and gives only integer quotient.
Assignment Operators
• These operators are useful to store the right side value into a left side
variable.
• let’s assume the values x = 20, y = 10 and z = 5:
Operator Example Meaning Result
= z = x+y Assignment operator. Stores right side value into left side variable, i.e. x+y is stored z = 30
into z.
+= z+=x Addition assignment operator. Adds right operand to the left operand and stores the z = 25
result into left operand, i.e. z = z+x.
-= z-=x Subtraction assignment operator. Subtracts right operand from left operand and z = -15
stores the result into left operand, i.e. z = z-x.
*= z*=x Multiplication assignment operator. Multiplies right operand with left operand and z = 100
stores the result into left operand, i.e. z = z *x.
/= z/=x Division assignment operator. Divides left operand with right operand and stores the z = 0.25
result into left operand, i.e. z = z/x.
%= z%=x Modulus assignment operator. Divides left operand with right operand and stores the z=5
remainder into left operand, i.e. z = z%x.
**= z**=y Exponentiation assignment operator. Performs power value and then stores the z= 9765625
result into left operand, i.e. z = z**y.
//= z//=y Floor division assignment operator. Performs floor division and then stores the z=0
result into left operand,
i.e. z = z// y.
• It is possible to assign the same value to two variables in the same
statement as:
a=b=1
print(a, b) # will display 1 1
• We can also assign values in different variable like:
a, b = 1, 2
print(a, b) # will display 1 2

Python does not have increment operator ( ++ ) and decrement operator


( -- ) that are available in C and Java.
Unary Minus Operator
• The unary minus operator is denoted by the symbol minus ( - ).
• When this operator is used before a variable, its value is negated.
• That means if the variable value is positive, it will be converted into
negative and vice versa.
n = 10
print(-n) # displays -10

num = -10
num = - num
print(num) # displays 10
Relational Operators
• Relational operators are used to compare two quantities.
• We can compare whether two values are same or which one is bigger or which
one is lesser, etc. using these operators.
• These operators will result in True or False depending on the values compared.
• There are 6 types of Relational operators.
• we are assuming a =1 and b = 2
Operator Example Meaning Result
> a>b Greater than operator. If the value of left operand is greater than the value of False
right operand, it gives True else it gives False.
>= a>=b Greater than or equal operator. If the value of left operand is greater or False
equal than that of right operand, it gives True else False.
< a<b Less than operator. If the value of left operand is less than the value of True
right operand, it gives True else it gives False.
<= a<=b Less than or equal operator. If the value of left operand is lesser or equal True
than that of right operand, it gives True else False.
== a==b Equals operator. If the value of left operand is equal to the value of right False
operand, it gives True else False.
!= a != b Not equals operator. If the value of the left operand is not equal to the value True
of right operand, it returns True else it returns False.
Logical Operators
• Logical operators are useful to construct compound conditions.
• A compound condition is a combination of more than one simple condition.
• Each of the simple condition is evaluated to True or False and then the decision is taken to know
whether the total condition is True or False.
• We should keep in mind that in case of logical operators, False indicates 0 and True indicates any
other number.
• There are 3 logical operators.
• Let’s take x = 1 and y=2
Operator Example Meaning Result

And x and y And operator. If x is False, it returns x, otherwise it returns y. 2

Or x or y Or operator. If x is False, it returns y, otherwise it returns x. 1

Not not x Not operator. If x is False, it returns True, otherwise True. False
x = 100
y = 200
print(x and y) # will display 200
print(x or y) # will display 100
print (not x) # will display False
x=1;
y=2;
z=3;
if(x<y and y<z): print('Yes')
else: print('No')
Output:
200
100
False
Yes
Boolean Operators
• We know that there are two ‘bool’ type literals.
• They are True and False. Boolean operators act upon ‘bool’ type
literals and they provide ‘bool’ type output.
• It means the result provided by Boolean operators will be again
either True or False.
• There are three Boolean operators.
Operator Example Meaning Result

and x and y Boolean and operator. If both x and y are True, then it False
returns True, otherwise False.

or x or y Boolean or operator. If either x or y is True, then it returns True


True, else False.

not not x Boolean not operator. If x is True, it returns False, else True. False
Bitwise Operators
• These operators act on individual bits (0 and 1) of the operands.
• There are 6 types of bitwise operators as shown below:
Bitwise AND operator (&)
Bitwise OR operator (|)
Bitwise XOR operator (^)
Bitwise Left shift operator (<<)
Bitwise Right shift operator (>>)
Bitwise Complement operator ( ~ )
Membership Operators
• The membership operators are useful to test for membership in a
sequence such as strings, lists, tuples or dictionaries.
• For example, if an element is found in the sequence or not can be
asserted using these operators.
• There are two membership operators :
in
not in
• The in operator returns True if an element is found in the specified
sequence. If the element is not found in the sequence, then it returns
False.
• The not in works in reverse manner for ‘in’ operator. This operator returns
True if an element is not found in the sequence. If the element is found,
then it returns False.
• Let’s take a group of strings in a list. We want to display the members of
the list using a for loop where the ‘in’ operator is used. The list of names
is given below:
names = [“Himanshu”, “Pant", “Gehu", “Bhimtal"]
• Here the list name is ‘names’. It contains a group of names. Suppose, we
want to retrieve all the names from this list, we can use a for loop as:
for name in names: print (name)

Output:
Himanshu
Pant
Gehu
Bhimtal
names = ["Himanshu", "Pant", "Gehu", "Bhimtal"]
check_list = ["Himanshu", "John", "Pant", "Alex"]

for name in check_list:


if name not in names:
print(name)

Output:
John
Alex
Identity Operators
• These operators compare the memory locations of two objects.
• Hence, it is possible to know whether the two objects are same or not.
• The memory location of an object can be seen using the id() function.
• This function returns an integer number, called the identity number that internally represents the memory location of the object.
• For example, id(a) gives the identity number of the object referred by the name ‘a’.
a = 25
b = 25
In the first statement, we are assigning the name (or identifier) ‘a’ to the object 25.
In the second statement, we are assigning another name ‘b’ to the same object 25.
In Python, everything is considered as an object.
Here, 25 is the object for which two names are given.
If we display an identity number of these two variables, we will get same numbers as they refer to the same object.
a=25
b=25
print(id(a))
print(id(b))
• Output:
2727359048752
2727359048752
There are two identity operators:
is
is not
The is Operator
• The ‘is’ operator is useful to compare whether two objects are same
or not.
• It will internally compare the identity number of the objects. If the
identity numbers of the objects are same, it will return True;
otherwise, it returns False.
The is not Operator
• This is not operator returns True, if the identity numbers of two
objects being compared are not same.
• If they are same, then it will return False.
• The ‘is’ and ‘is not’ operators do not compare the values of the objects.
• They compare the identity numbers or memory locations of the objects.
• If we want to compare the value of the objects, we should use equality
operator ( == ).
a = 25
b = 25
if(a is b):
print("a and b have same identity")
else:
print("a and b do not have same identity")
Output:
a and b have same identity
one = [1,2,3,4]
two = [1,2,3,4]
if(one is two):
print("one and two are same")
else:
print("one and two are not same")
Output:
one and two are not same
• In the above example, the lists one and two are having same elements or values. But the output
is “one and two are not same”. The reason is this: ‘is’ operator does not compare the values. It
compares the identity numbers of the lists.
print(id(one))
print(id(two))
Output:
1998595699584
1998586724288
• Since both the lists are created at different memory locations, we have
their identity numbers different.
• So, ‘is’ operator will take the lists ‘one’ and ‘two’ as two different lists even
though their values are same.
• It means, ‘is’ is not comparing their values.
• We can use equality ( == ) operator to compare their values as:
if(one == two):
print("one and two are same")
else:
print("one and two are not same")
• Output:
one and two are same
Mathematical Functions
• In Python, a module is a file that contains a group of useful objects like
functions, classes or variables.
• ‘math’ is a module that contains several functions to perform mathematical
operations.
• If we want to use any module in our Python program, first we should import
that module into our program by writing ‘import’ statement.
• To import ‘math’ module, we can write import math
• Once this is done, we can use any of the functions available in math module.
Now, we can refer to sqrt() function from math module by writing module name
before the function as: math.sqrt().
x = math.sqrt(16) #output is 4
• We can also use import statement as: import math as m
x = m.sqrt(16)
INPUT AND OUTPUT
• To provide input to a computer, Python provides some statements which
are called Input statements. Similarly, to display the output, there are
Output statements available in Python. We should use some logic to
convert the input into output.

• Output statements
• Input statements
Output statements
• To display output or results, Python provides the print() function. This function can
be used in different formats which are discussed hereunder.
The print() Statement
• When the print() function is called simply, it will throw the cursor to the next line. It
means that a blank line will be displayed.
The print(“string”) Statement
• A string represents a group of characters. When a string is passed to the print()
function, the string is displayed as it is.
print("Hello")
Hello
• In case of strings, double quotes and single quotes have the same meaning and
hence can be used interchangeably.
print('Hello')
Hello
• We can use escape sequence characters inside the print() function. An
escape sequence is a character that contains a special meaning. For
example, ‘\n’ indicates new line. ‘\t’ represents tab space.
print("This is the \nfirst line")
This is the
first line

print("This is the \tfirst line")


This is the first line
• To escape the effect of escape sequence, we should add one more ‘\’
(backslash) before the escape sequence character. For example, \\n
displays ‘\n’ and \\t displays ‘\t’.
print("this is the \\nfirst line")
this is the \nfirst line
• We can use repetition operator ( * ) to repeat the strings in the output as:
print(3*'Hello')
HelloHelloHello
• The operator ‘+‘ when used on numbers will perform addition operation.
The same ‘+‘ will not do addition operation on strings as it is not possible
to perform arithmetic operations on strings. When we use ‘+‘ on strings, it
will join one string with another string. Hence ‘+‘ is called concatenation
(joining) operator when used on strings.
print("Hello"+"BCA") #HelloBCA
• The ‘+’ operator in the preceding statement joined the two strings without
any space in between. We can also write the preceding statement by
separating the strings using ‘, ‘ as:
print("Hello","BCA") #Hello BCA
Control Statements
• Control statements are statements which control or change the flow of
execution. The following are the control statements available in Python:
if statement
if … else statement
if … elif … else statement
while loop
for loop
else suite
break statement
continue statement
pass statement
assert statement
return statement
The if Statement
• This statement is used to execute one or more statement depending
on whether a condition is True or not.
• The syntax or correct format of if statement is given below:
if condition:
statements
• First, the condition is tested. If the condition is True, then the
statements given after colon (:) are executed.
• We can write one or more statements after colon (:). If the condition
is False, then the statements mentioned after colon are not executed.
A Python program to express a digit in a word.
# understanding if statement
num=1
if num==1:
print("One")

Output:
C:\>python Demo.py
One
• We can also write a group of statements after colon.
• The group of statements in Python is called a suite.
• While writing a group of statements, we should write them all with proper indentation.
• Indentation represents the spaces left before the statements.
• The default indentation used in Python is 4 spaces.
Program : A Python program to display a group of messages when the condition is true.
# understanding if statement
str = 'Yes‘
if str == 'Yes':
print("Yes")
print("This is what you said")
print("Your response is good")

C:\>python Demo.py
Yes
This is what you said
Your response is good
The if … else Statement

• The if … else statement executes a group of statements when a condition


is True; otherwise, it will execute another group of statements.
• The syntax of if … else statement is given below:
if condition:
statements1
else:
statements2
If the condition is True, then it will execute statements1 and if the
condition is False, then it will execute statements2. It is advised to use 4
spaces as indentation before statements1 and statements2.
Program : A Python program to test whether a
number is even or odd.
# to know if a given number is even or odd
x = int(input("Enter a number: "))
if x % 2 == 0:
print(x, " is even number")
else:
print(x, " is odd number")
The if … elif … else Statement
• Sometimes, the programmer has to test multiple conditions and execute statements
depending on those conditions.
• if … elif … else statement is useful in such situations.
• Consider the following syntax of if … elif … else statement:
if condition1:
statements1
elif condition2:
statements2
elif condition3:
statements3
else:
statements4
• When condition1 is True, the statements1 will be executed. If condition1 is False, then condition2 is
evaluated. When condition2 is True, the statements2 will be executed. When condition2 is False, the
condition3 is tested. If condition3 is True, then statements3 will be executed. When condition3 is False,
the statements4 will be executed. It means statements4 will be executed only if none of the conditions
are True.
The while Loop
• A statement is executed only once from top to bottom.
• For example, ‘if’ is a statement that is executed by Python interpreter only once. But a
loop is useful to execute repeatedly.
• The while loop is useful to execute a group of statements several times repeatedly
depending on whether a condition is True or False.
initialization
while condition:
statements
updation
Here, ‘statements’ represents one statement or a suite of statements. Python interpreter
first checks the condition. If the condition is True, then it will execute the statements
written after colon ( : ). After executing the statements, it will go back and check the
condition again. If the condition is again found to be True, then it will again execute the
statements. Then it will go back to check the condition once again. In this way, as long as
the condition is True, Python interpreter executes the statements again and again. Once
the condition is found to be False, then it will come out of the while loop.
Program : A Python program to display even
numbers between 100 and 200.
# to display even numbers between 100 and 200
x=100
while x>=100 and x<=200:
print(x)
x+=2
Program : A Python program to display
numbers from 1 to 10 using while loop.
# to display numbers from 1 to 10
x=1
while x<=10:
print(x)
x+=1
print("End")
The for Loop
• The for loop is useful to iterate over the elements of a sequence.
• It means, the for loop can be used to execute a group of statements repeatedly
depending upon the number of elements in the sequence.
• The for loop can work with sequence like string, list, tuple, range etc.
• The syntax of the for loop is given below:
for var in sequence:
statements
• The first element of the sequence is assigned to the variable written after ‘for’ and then
the statements are executed. Next, the second element of the sequence is assigned to
the variable and then the statements are executed second time. In this way, for each
element of the sequence, the statements are executed once. So, the for loop is
executed as many times as there are number of elements in the sequence.
Program : A Python program to display characters
of a string using for loop.
# to display each character from a string
str='Hello'
for ch in str:
print(ch)
• In the above program, the string ‘str’ contains ‘Hello’. There are 6 characters in
the string. The for loop has a variable ‘ch’. First of all, the first character of the
string, i.e. ‘H’ is stored into ch and the statement, i.e. print(ch) is executed. As a
result, it will display ‘H’. Next, the second character of the string, i.e. ‘e’ is stored
into ch. Then print(ch) is once again executed and ‘e’ will be displayed. In the
third iteration, the third character ‘l’ will be displayed. In this way the for loop is
executed for 6 times and all the 6 characters are displayed in the output.
Program : A Python program to display odd
numbers from 1 to 10 using range() object.
# to display odd numbers between 1 and 10
for i in range(1, 10, 2):
print(i)

Program : A program to display numbers from 10 to 1 in descending


order.
for x in range (10, 0, -1):
print(x)
Program : A program to display the elements of a
list using for loop.
list = [10,20.5,'A','America']
for element in list:
print(element)
Program : A Python program to display and find the sum of a list of
numbers using for loop.
list = [10,20,30,40,50]
sum=0
for i in list:
print(i)
sum+=i
print('Sum= ', sum)
Program : A Python program to display and sum of
a list of numbers using while loop.
list = [10,20,30,40,50]
sum=0
i=0
while i <len(list):
print(list[i])
sum+=list[i]
i+=1
print('Sum= ', sum)
Infinite Loops
• In the while loop, what happens if we forget to write the last statement, i.e. ‘i+=1’?
The initial ‘i’ value 1 is displayed first, but it is never incremented to reach 10.
• Hence this loop will always display 1 and never terminates. Such a loop is called
‘infinite loop’. An infinite loop is a loop that executes forever.
i=1
while i<=10:
print(i)
• It will display the value 1 forever.
• To stop the program, we have press Control+C at system prompt.
• Another way of creating an infinite loop is to write ‘True’ in the condition part of the
while loop so that the Python interpreter thinks that the condition is True always and
hence executes it forever.
while(True):
print("Hai")
Nested Loops
• It is possible to write one loop inside another loop.
• For example, we can write a for loop inside a while loop or a for loop inside another for loop.
• Such loops are called ‘nested loops’.
for i in range(1, 11): # to display 10 rows
for j in range(1, i+1): # no. of stars = row number
print('* ', end='')
print()
*
**
***
****
*****
******
*******
********
*********
**********
print('* ', end='')

This will display the star symbol. The end=’’ represents that it should
not throw the cursor to the next line after displaying each star. So, all
the stars are displayed in the same line. But we need to throw the
cursor into the next line when there is a new row starting, i.e. when i
value changes. This can be achieved by another print() statement in the
outer for loop that does not display anything but simply throws the
cursor into the next line.
The break Statement
• The break statement can be used inside a for loop or while loop to come
out of the loop.
• When ‘break’ is executed, the Python interpreter jumps out of the loop to
process the next statement in the program.
• Program : A Python program to display numbers from 10 to 6 and break
the loop when the number about to display is 5.
x = 10
while x>=1:
print ('x= ', x)
x-=1
if x==5: # if x is 5 then come out from while loop
break
print("Out of loop")
FUNCTIONS
• function is similar to a program that consists of a group of statements
that are intended to perform a specific task.
• Thus when there are several tasks to be performed, the programmer
will write several functions.
• Once a function is written, it can be reused as and when required. So
functions are also called reusable code. Because of this reusability,
the programmer can avoid code redundancy. It means it is possible to
avoid writing the same code again and again.
• When there is an error in the software, the corresponding function
can be modified without disturbing the other functions in the
software. Thus code debugging will become easy.
• Built-in function
• User define function
Difference between a Function and a Method
• A function contains a group of statements and performs a specific
task.
• A function can be written individually in a Python program.
• A function is called using its name.
• When a function is written inside a class, it becomes a ‘method’.
• A method is called using one of the following ways:
objectname.methodname()
Classname.methodname()
• A function and a method are same except their placement and the
way they are called.
Defining a Function
• We can define a function using the keyword def followed by function name.
• After the function name, we should write parentheses ( ) which may contain
parameters.

• Here, ‘def’ represents the starting of function definition. ‘sum’ is the name of the
function. After this name, parentheses ( ) are compulsory as they denote that it is a
function and not a variable or something else. In the parentheses, we wrote two
variables ‘a’ and ‘b’. These variables are called ‘parameters’.
• After parentheses, we put a colon ( : ) that represents the beginning of the function
body.
• After writing the docstring in the function, the next step is to write the logic of the
function.
Calling a Function
• A function cannot run on its own.
• It runs only when we call it. So, the next step is to call the function using
its name.
• While calling the function, we should pass the necessary values to the
function in the parentheses as:
sum(10, 15)
• Here, we are calling the ‘sum’ function and passing two values 10 and 15
to that function. When this statement is executed, the Python interpreter
jumps to the function definition and copies the values 10 and 15 into the
parameters ‘a’ and ‘b’ respectively. These values are processed in the
function body and result is obtained. The values passed to a function are
called ‘arguments’. So, 10 and 15 are arguments.
Program: A function that accepts two values and
finds their sum.
# a function to add two numbers
def sum(a, b):
""" This function finds sum of two numbers """
c = a+b
print('Sum= ', c)
# call the function
sum(10, 15)
sum(1.5, 10.75) # call second time

• Output:
Sum= 25
Sum= 12.25
Returning Results from a Function
• We can return the result or output from the function using a ‘return’ statement in the body of the
function.
Program : A Python program to find the sum of two numbers and return the result from the function.
def sum(a, b):
c = a+b
return c
# call the function
x = sum(10, 15)
print('The sum is: ', x)
y = sum(1.5, 10.75)
print('The sum is: ', y)

Output:
The sum is: 25
The sum is: 12.25
Program : A function to test whether a number is
even or odd.
def even_odd(num):
""" to know num is even or odd """
if num % 2 == 0:
print(num," is even")
else:
print(num," is odd")

# call the function


n=int(input("Enter the number="))
even_odd(n)
n=int(input("Enter the number="))
even_odd(n)

Output:
Enter the number=5
5 is odd
Enter the number=2
2 is even
Program : A Python program to calculate
factorial values of numbers.
def fact(n):
""" to find factorial value """
f=1
while n>=1:
f*=n
n-=1
return f

n=int(input("Enter any number="))


print('Factorial of {} is {}'.format(n, fact(n)))

Output:
Enter any number=5
Factorial of 5 is 120
Returning Multiple Values from a Function
• A function returns a single value in the programming languages like C or Java. But in Python, a function can return
multiple values. When a function calculates multiple results and wants to return the results, we can use the return
statement as:
return a, b, c
Program : A Python program to understand how a function returns two values.
def sum_sub(a, b):
""" this function returns results of addition and subtraction of a, b """
c=a+b
d=a-b
return c, d

x, y = sum_sub(10, 5)
print("Result of addition: ", x)
print("Result of subtraction: ", y)

Output:
Result of addition: 15
Result of subtraction: 5
Formal and Actual Arguments
• When a function is defined, it may have some parameters.
• These parameters are useful to receive values from outside of the
function. They are called ‘formal arguments’.
• When we call the function, we should pass data or values to the
function. These values are called ‘actual arguments’.
def sum(a, b): # a, b are formal arguments
c = a+b
print(c)
# call the function
x=10; y=15
sum(x, y) # x, y are actual arguments
• The actual arguments used in a function call are of 4 types:
Positional arguments
Keyword arguments
Default arguments
Variable length arguments
Positional Arguments
• These are the arguments passed to a function in correct positional order. Here, the number of
arguments and their positions in the function definition should match exactly with the number
and position of the argument in the function call.
# positional arguments demo
def pos(s1, s2):
""" to join s1 and s2 and display total string """
s3 = s1+s2
print('Total string: ‘,s3)

pos('New', 'York') # positional arguments

• This function expects two strings that too in that order only.
• if we call the function by passing 3 strings in above function, it will generate an error.
pos(‘New’, ‘York’, City’) #generate error
Keyword Arguments
• Keyword arguments are arguments that identify the parameters by their
names.
def grocery(item, price):
""" to display the given arguments """
print('Item =’, item)
print('Price =' , price)
# call grocery() and pass 2 arguments
grocery(item='Sugar', price=50.75) # keyword arguments
grocery(price=88.00, item='Oil') # keyword arguments

• In this way, even though we change the order of the arguments, there will
not be any problem as the parameter names will guide where to store that
value.
Default Arguments
• We can mention some default value for the function parameters in the definition.
def grocery(item, price=40.00):
""" to display the given arguments """
print('Item = ‘, item)
print('Price = ‘, price)

grocery(item='Sugar', price=50.75) # pass 2 arguments


grocery(item='Sugar') # default value for price is used.

Output:
Item = Sugar
Price = 50.75
Item = Sugar
Price = 40.00
• Here, the first argument is ‘item’ whose default value is not mentioned. But the second argument is ‘price’
and its default value is mentioned to be 40.00. At the time of calling this function, if we do not pass ‘price’
value, then the default value of 40.00 is taken. If we mention the ‘price’ value, then that mentioned value is
utilized.
Variable Length Arguments
• Sometimes, the programmer does not know how many values a
function may receive. In that case, the programmer cannot decide
how many arguments to be given in the function definition.
• A variable length argument is an argument that can accept any
number of values. The variable length argument is written with a ‘ * ’
symbol before it in the function definition.
def add(farg, *args):
• Here, ‘farg’ is the formal argument and ‘*args’ represents variable
length argument. We can pass 1 or more values to this ‘*args’ and it
will store them all in a tuple.
Program : A Python program to show variable length argument and its
use.
def add(farg, *args): # *args can take 0 or more values
""" to add given numbers """
print('Formal argument= ', farg)
sum=0
for i in args: Output:
Formal argument= 5
sum+=i Sum of all numbers= 15
Formal argument= 5
print('Sum of all numbers= ',(farg+sum)) Sum of all numbers= 15
add(5, 10) Sum of all numbers= 35
Sum of all numbers= 65
add(5, 10, 20, 30)
Recursive Functions
• A function that calls itself is known as ‘recursive function’.
Program : A Python program to calculate factorial values using recursion.

def factorial(n):
""" to find factorial of n """
if n==0:
result=1
else:
result=n*factorial(n-1)
return result

n=int(input("Enter the no="))


print('Factorial of {} is {}'.format(n, factorial(n)))
Anonymous Functions or Lambdas
• A function without a name is called ‘anonymous function’.
• So far, the functions we wrote were defined using the keyword ‘def’.
But anonymous functions are not defined using ‘def’.
• They are defined using the keyword lambda and hence they are also
called ‘Lambda functions’.
def square(x):
return x*x
The same function can be written as anonymous function as:
lambda x: x*x
lambda argument_list : expression
Program : A Python program to create a lambda function that
returns a square value of a given number.

f = lambda x: x*x # write lambda function


value = f(5) # call lambda function
print('Square of 5 = ', value) # display result

Program : A lambda function to calculate the sum of two numbers.


f = lambda x, y: x+y # write lambda function
result = f(1.55, 10) # call lambda function
print('Sum = ', result) # display result
CLASSES AND OBJECTS
• Class is a model to create objects.
• This means, we write a class with the attributes and actions of objects.
• Attributes are represented by variables and actions are performed by methods.
So, a class contains variable and methods.
• The same variables and methods are also available in the objects because they
are created from the class.
• These variables are also called ‘instance variables’ because they are created
inside the instance (i.e. object).
• Please remember the difference between a function and a method. A function
written inside a class is called a method. Generally, a method is called using one
of the following two ways:
classname.methodname()
instancename.methodname()
Creating a Class
• A class is like a blueprint or template used to create objects.
• Objects are things that have data (variables) and functions (methods).
• class=attributes + methods
Basic Syntax of a Class

class ClassName:
# data members and methods
def method_name(self):
# code
Example:
class Student:
def show(self):
print("This is a student class")
Creating an Object
• An object is created from a class to use its data and methods.
obj = ClassName()
obj.method_name()

• Observe the parameter ‘self’ written after the method name in the parentheses.
• ‘self’ is a variable that refers to current class instance.

Example:
s1 = Student()
s1.show()

Output:
This is a student class
Using Class Without __init__() Function
• __init__() is not compulsory.
• You can create a class and assign values manually to the object.

class Student:
def show(self):
print("Name:", self.name)
print("Age:", self.age)

s1 = Student()
s1.name = “Himanshu"
s1.age = 20
s1.show()

Output:
Name: Himanshu
Age: 20
Using Class With __init__() Function
• __init__() is a special method (constructor).
• It runs automatically when you create an object.
• It is used to initialize data members.

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

def show(self):
print("Name:", self.name)
print("Age:", self.age) Output:

Name: Himanshu
s1 = Student("Himanshu", 20) Age: 20
s1.show()
The Self Variable

• ‘self’ is a default variable that contains the memory address of the


instance of the current class.
• So, we can use ‘self’ to refer to all the instance variables and instance
methods.
• We use ‘self’ in two ways:
• The ‘self’ variable is used as first parameter in the constructor as:
def init (self):
• ‘self’ can be used as first parameter in the instance methods as:
def talk(self):
Constructor
• A constructor is a special method in a class that runs automatically when an
object is created.
• It is used to initialize object attributes (i.e., assign values to variables) at the
time of object creation.
• In Python, the constructor method is named __init__().
• Every Class can have only one __init__() method.

Syntax of a Constructor

class ClassName:
def __init__(self, parameters):
# initialization code
Types of Constructors
• There are two types of constructors in Python:

1. Default Constructor: A constructor with only self as a parameter (no extra arguments).
2. Parameterized Constructor: A constructor that accepts additional parameters to
initialize object variables.
Default Constructor Example
class Demo:
def __init__(self):
print("This is a default constructor!")
# Object creation
obj = Demo()

Output:
This is a default constructor!

Explanation:
•The constructor is called automatically when the object obj is created.
•Since no parameters are used, it is called a default constructor.
Parameterized Constructor Example
class Student:
def __init__(self, name, age):
self.name = name # initialize object attribute
self.age = age
def show_info(self):
print("Student Name:", self.name)
print("Student Age:", self.age)
# Creating object and passing values
s1 = Student(“Himanshu", 30)
s1.show_info()
Output:
Student Name: Himanshu
Student Age: 30
Inheritance
• Inheritance is a fundamental concept of Object-Oriented Programming (OOP) that
allows a new class (child or derived class) to reuse the properties and methods of
an existing class (parent or base class).
• It promotes code reusability and reduces redundancy.
• The child class can add new features or override existing ones.
• It supports creating a hierarchical relationship between classes.
Basic Syntax of Inheritance
class ParentClass:
# properties and methods

class ChildClass(ParentClass):
# inherits properties and methods from ParentClass
Types of Inheritance in Python

Type Description
Single Inheritance One class inherits from another.

Multilevel Inheritance A class inherits from a child class.

Multiple Inheritance A class inherits from multiple parent classes.

Hierarchical Inheritance Multiple classes inherit from the same parent class.

Hybrid Inheritance A combination of two or more types of inheritance.


Single Inheritance
class A:
def Show(self):
print("Show Class")

class B(A):
def Display(self):
print("Display Class")

s = B()
s.Show()
s.Display()

Output:
Show Class
Display Class
Multilevel Inheritance
class A:
def Show(self):
print("Show Class")

class B(A):
def Display(self):
print("Display Class")
class C(B):
def Output(self):
print("Output Class")
s = C()
s.Show()
s.Display()
s.Output()

Output:
Show Class
Display Class
Output Class
Multiple Inheritance
class A:
def Show(self):
print("Show Class")
class B:
def Display(self):
print("Display Class")
class C(A,B):
def Output(self):
print("Output Class")
s = C()
s.Show()
s.Display()
s.Output()

Output:
Show Class
Display Class
Output Class
class A:
Hierarchical Inheritance
def Show(self):
print("Show Class")
class B(A):
def Display(self):
print("Display Class")
class C(A):
def Output(self):
print("Output Class")
s = C()
d=B()
s.Show(); s.Output()
d.Display(); d.Show()

Output:
Show Class
Output Class
Display Class
Show Class
Hybrid Inheritance
class A:
def showA(self):
print("Class A")
class B(A):
def showB(self):
print("Class B")
class C(A):
def showC(self):
print("Class C")
class D(B, C):
def showD(self):
print("Class D") Output:
d = D()
d.showA() Class A
d.showB() Class B
Class C
d.showC() Class D
d.showD()
The super() Method
• super() is a built-in method which is useful to call the super class
constructor or methods from the sub class.
• Any constructor written in the super class is not available to the sub
class if the sub class has a constructor.
• We can call the super class constructor using the super() method
from inside the sub class constructor.
• When we override the __init__() constructor in a child class, we can
still call the parent’s constructor using super().

super(). init () # call super class constructor


super(). init (arguments) # call super class constructor and pass # arguments
super().method() # call super class method
Using super() with Constructors (__init__())
class ABC:
def __init__(self, name):
self.name = name
print("ABC constructor called")

class XYZ(ABC):
def __init__(self, name, address):
super().__init__(name) # calling parent class constructor
self.address = address
print("XYZ constructor called")

d = XYZ("Himanshu", "haldwani")
print(d.name, d.address)

Output:
ABC constructor called
XYZ constructor called
Himanshu haldwani
Using super() to Call Parent Methods
class ABC:
def show(self):
print("ABC class show function")
class XYZ(ABC):
def show(self):
super().show() # calling parent class method
print("XYZ class Show function")
d = XYZ()
d.show()

Output:
ABC class show function
XYZ class Show function

You might also like