Python Unit 1 2 3
Python Unit 1 2 3
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:
• 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).
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
• 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.
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
print(s[11:]) # display from 11th characters onwards till end Core Python
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 \
\b backspace
\r Enter
\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
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
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.
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"]
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
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
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")
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
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)
• 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)
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
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
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.
Hierarchical Inheritance Multiple classes inherit from the same parent 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().
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