Notes Python
Notes Python
LEARN COURSE
Python Programming
PYTHON
QUICKLY
A Complete Beginner’s Guide to Learning
Python, Even If You’re New to Programming
TABLE OF CONTENTS
• Introduction Page: 3
➢ Why python…?
➢ Benefits / features of Python.
➢ Role of PVM
➢ Job Opportunities.
• Python Syntax Page: 8
➢ Basic Syntax
➢ Variable
➢ Comments
➢ Keywords
• Data Types Page: 11
➢ Fundamental Data Type
➢ Sequential Data Type
➢ Collection Data Type
➢ None Data Type
➢ Type Casting Techniques
➢ Number Base Conversion
• Development of Program in Python Page: 50
➢ Reading And Writing Data in Python
• Operators Page: 51
➢ Arithmetic Operator
➢ Assignment Operator
➢ Relational Operator
➢ Logical Operator
➢ Bitwise Operator
➢ Membership Operator
➢ Logical Operator
➢ Identity Operator
• Introduction to Flow Control Statement Page: 62
➢ Conditional Statements
➢ Looping Statements
➢ Misc. Flow statements
1|Page
• Functional Programming in Python Page: 80
➢ Defining Function
➢ Function Argument
➢ Anonymous or Lambda Function
➢ Special Function
• Object Oriented Programming Concept in Python Page: 96
➢ Class
➢ Object
➢ Inheritance
➢ Polymorphism
• Modules in Python Page: 107
➢ Built-in Modules in Python
➢ User-define Modules in Python
➢ Re-using Modules in Python
• File Handling in Python Page: 113
➢ File Opening Modes in Python
➢ Reading and Writing Data File in Python
• Exceptional Handling in Python Page: 119
➢ Programming using Exception Handling
➢ Types of Exceptions
➢ Exception Handling with File Operation
• OS Module in Python Page: 130
➢ Create Folder by using OS Module
➢ Delete Folder by using OS Module
• Packages in Python Page: 131
➢ Approach Towards Packages
2|Page
INTRODUCTION
FEATURES OF PYTHON:
3|Page
1) Easy To Learn and Readable Language:
• Python is extremely easy to learn.
• Its syntax is super simple and the learning curve of Python is very smooth.
• It is extremely easy to learn and code in Python and the indentation used instead of
curly braces in Python makes it very easy to read Python code.
• Perhaps, because of this a lot of schools and universities, and colleges are teaching
Python to their students who are beginning their journey with coding.
2) Easy to Code:
• Python is a very high-level programming language, yet it is effortless to learn.
• Anyone can learn to code in Python in just a few hours or a few days.
• Mastering Python and all its advanced concepts, packages and modules might take
some more time.
• However, learning the basic Python syntax is very easy, as compared to other
popular languages like C, C++, and Java.
3) Interpreted language:
• Python code is not compiled at once, converted to a .exe file, and then executed.
• Python is an interpreted language which means its code is executed line by line and
not all at once like in other programming languages.
• This line-by-line execution also makes it easy to debug the code.
4) Free and Open Source:
• Python is developed under an OSI-approved open-source license.
• Hence, it is completely free to use, even for commercial purposes.
• It doesn't cost anything to download Python or to include it in your application.
• It can also be freely modified and re-distributed.
• Python can be downloaded from the official Python website.
5) Object-Oriented Language:
• A programming language is object-oriented if it focuses design around data and
objects, rather than functions and logic.
• On the contrary, a programming language is procedure-oriented if it focuses more
on functions (code that can be reused).
• One of the critical Python features is that it supports both object-oriented and
procedure-oriented programming.
4|Page
6) Portable:
• Python is portable in the sense that the same code can be used on different
machines.
• Suppose you write a Python code on a Mac. If you want to run it on Windows or
Linux later, you don’t have to make any changes to it.
• As such, there is no need to write a program multiple times for several platforms.
7) Extensible:
• A programming language is said to be extensible if it can be extended to other
languages.
• Python code can also be written in other languages like C++, making it a highly
extensible language.
8) Databases:
• Python provides interfaces to all major commercial databases.
9) Support for GUI:
• One of the key aspects of any programming language is support for GUI or
Graphical User Interface.
• A user can easily interact with the software using a GUI. Python offers various
toolkits, such as Tkinter, wxPython and JPython, which allows for GUI's easy and
fast development.
10) High-level Language:
• Python is a high-level programming language because programmers don’t need to
remember the system architecture, nor do they have to manage the memory.
• This makes it super programmer-friendly and is one of the key features of Python.
11) Dynamically Typed:
• Many programming languages need to declare the type of the variable before
runtime. With Python, the type of the variable can be decided during runtime.
• This makes Python a dynamically typed language. For example, if you have to
assign an integer value 20 to a variable “x”, you don’t need to write int x = 20. You
just have to write x = 15.
5|Page
PYTHON CAREER OPPORTUNITIES:
• Python Developer.
• Data Scientist.
• Artificial Intelligence & Machine Learning Engineer.
Python Skills
After knowing all the opportunities that Python holds, its good to know all the ins and
out to it. Focus is always on skill first so that you stand out amongst others. They can be
broken down as follows:
• Core Python (Basic knowledge between Python 2 and Python 3 is sufficient,
complete knowledge of all modules is not required).
• Web Frameworks (Learn common Python frameworks such as Django or Pandas).
• Object-relational mappers (Ability to connect to the database with the help of
ORM rather than SQL).
• Understand Multiprocess Architecture (Ability to write and manage threads for
high-performance).
• RESTful APIs (understand how to use them and able to integrate components with
them).
• Building Python Applications (One should know how to package up a code and
deployment and release).
• Good communication and designing skills (Able to communicate well with
members as well as implement servers that are scalable, secure and highly
available).
6|Page
ROLE OF PVM (Python Virtual Machine):
• When we run a Python program, two steps happen,
The code gets converted to another representation called ‘Byte Code’.
‘Byte Code’ gets converted to Machine Code (which is understandable by the computer)
• The second step is being done by PVM or Python Virtual Memory. So PVM is
nothing but a software/interpreter that converts the byte code to machine code for
given operating system.
• PVM is also called Python Interpreter and this is the reason Python is called an
Interpreted language.
• We can’t see the Byte Code of the program because this happens internally in memory.
• But if we want to see the byte code of the program execute the below command:
D:\> python -m py_complie [Link]
• Here we are calling the Python compiler with the -m option. -m represents module and
the module name is py_complie. This module generates the .pyc file for .py file.
• *.pyc file contains the byte code of the Python program. One can open and see the byte
code representation of the python program. To convert byte code into machine
code/output use:
D:\> python <nameofpycfile>.pyc
• Here Python would skip the step of byte code generation and would convert byte code
directly to machine code.
• That’s the reason, while delivering python projects, *.pyc files are given with PVM
so that users can see the output directly.
7|Page
PYTHON SYNTAX
BASIC SYNTAX
• Python syntax can be executed by writing directly in the Command Line:
Example: Print (“Hello, World!)
Output: Hello, World!
• Or by creating a python file on the server, using the .py file extension, and running it
in the Command Line:
VARIABLE
• When you develop a program, you need to manage values, a lot of them. To store
values, you use variables.
• In Python, a variable is a label that you can assign a value to it. And a variable is always
associated with a value.
For example:
8|Page
• A variable is a label that you can assign a value to it. The value of a variable can change
throughout the program.
• Use the variable_name = value to create a variable.
• The variable names should be as concise and descriptive as possible. Also, they should
adhere to Python variable naming rules.
COMMENTS IN PYTHON
• Comments are descriptions that help programmers better understand the intent and
functionality of the program.
• They are completely ignored by the Python interpreter.
• Everything that comes after # is ignored. So, we can also write the above program in a
single line as:
Example: print('Hello world’) #printing a string
Output: Hello world
• The interpreter ignores all the text after #.
KEYWORDS
Python has a set of keywords that are reserved words that cannot be used as variable names,
function names, or any other identifiers:
9|Page
True class finally is return
__peg_parser__
Low Level:
In this lang. we represented the data in the form of binary, hex, octa which are
understandable various devices. and they are not directly understandable by humans this is
called as low-level language.
High Level:
The low-level prog. lang data reprenstation is automatically converted into high level
understandable format in known high level prog. lang.
10 | P a g e
Data representation of python:
• We know that with the help of data type, memory spaced is created and input gets
stored.
• We must some distinct name to created memory space.
• Hence the distinct names make us to identify the value and present into memory space
and they are called "Identifier".
• Identifier values are changing during execution of program and they are called as
"Variables”. (Example: - a=10, if "a" is variable.)
• hence every input of program must be store in variables.
• "Hence to represent the DATA in python we need data types and variables."
DATA TYPES
Purpose is that to store the input in the memory by allocated memory spaced. Total no of data
types in python is 14.
11 | P a g e
FUNDAMENTAL DATA TYPE:
• purpose of this data type is to store single value in main memory.
• we have 4 fundamental data types in python.
• like as int, float, bool, complex.
1) INTEGERS IN PYTHON:
• Integer data type is used for storing integer value / whole number.
• They are often called just integers or ints.
• They are positive or negative whole numbers with no decimal point.
• Integers in Python 3 are of unlimited size.
Example:
# Printing an integer in Python
num = 5
print("number =", num)
Output: number = 5
• int data also stores different numbers system data.
• we have 4 types of numbers system: Decimal, Binary, Octal and Hexadecimal.
➢ Binary Number System:
Digits: 0 1 Base: 2
Example: a=10
b=bin(a)
print(b)
Output: 0b1010
12 | P a g e
➢ Octal number system:
Digits: 0 1 2 3 4 5 6 7. Base: 8
Example: a=17
b=oct(a)
print(b)
Output: 0o21
Example:
# Printing a floating point number in Python
num = 5.55
print("number =", num)
Output: number = 5.55
3) BOOLEANS IN PYTHON:
• Its mentioned only is True or False.
• The purpose of data type is that to store the True or False. (Logical value)
internally the Boolean value True is consider as 1. and Boolean value False is 0.
• On the value of bool data type, we can perform all type of operation.
• A Boolean data type is declared with the bool keyword and can only take the values
true or false.
• When the value is returned, true = 1 and false = 0.
13 | P a g e
4) COMPLEX NUMBERS IN PYTHON:
• Purpose of this data type is that to store the complex data.
• General Format: a+bj or a-bj here, "a" is called "REAL" part and "b" is called
"IMAGINARY".
• Internally the REAL and IMAGINARY part treated as Float type.
• To extract the REAL and IMAGINARY part from complex object, we used to
predefine attributes, they are REAL and IMAGINARY.
Example:
a= 2+3j
print([Link])
print([Link])
Output: 2.0
3.
STRINGS IN PYTHON
14 | P a g e
Syntax 2:
a= “Barak Obama”
2) Multi line String Data: to organise Multi line str data we use either use triple double
and triple single quote.
Syntax 1:
a= ’’’Aadi Manav
Jail road,
Nashik road’’’
Syntax 2:
a= ””” Aadi Manav
Jail road,
Nashik road”””
Example:
a = ‘KAUSTUBH’
Forward indexing-----------------------------------------------→
0 1 2 3 4 5 6 7
K A U S T U B H
-8 -7 -6 -5 -4 -3 -2 -1
------------------------------------------------------------------Reverse indexing
Slicing:
• The process of obtaining range of character / sub string from str object is called String
Slicing.
15 | P a g e
• A slice object is used to specify how to slice a sequence.
• You can specify where to start the slicing, and where to end.
Syntax 1:
Strobj [begin: end]
• This syntax given range of character from Begin Index to End – 1 Index provided.
[Begin < End otherwise we never get any result].
Syntax 2:
Strobj [Begin:]
• In this syntax we didn’t specify the end index in that PVM take overall string object
length as end index.
Syntax 3:
Strobj [: End]
• In this syntax we didn’t specify begin index then PVM takes initial index as begin index.
• Positive or negative for end index it will take n-1 value.
Syntax 4:
Strobj [Begin: End: Step]
RULES
• Here, ‘Begin’, ‘End’ and ‘Step’ values can be Positive or Negative.
• If the value of step is positive (+) then we must consider the elements from begin to end-
1 in forward direction provided Begin<End.
• If the value of ‘step’ is negative (-) then we must consider the elements from begin to
end+1 in backward direction provided Begin > End.
• if we are retrieving the element in forward direction and if end value is zero then we get
empty result.
16 | P a g e
• Syntax:
Variable Name = [Link] ()
Program 1: a="barak obama"
print([Link]())
Output: Barak obama
➢ title ():
• This function is used `converting first letter of every word into capital of given string
data.
• Syntax:
Variable Name = [Link]()
Program, 1: a="venkata satyanarayana prabhas raju uppalapati"
a1=[Link]()
print(a1)
Output: Venkata Satyanarayana Prabhas Raju Uppalapati
➢ find ():
• This function is used finding the index of first occurrence of specific word / letter.
• Syntax:
➢ isalnum ():
• This return “True” provided str data is a combination of str or digit or both.
(alphabets a-z and numbers 0-9)
• This return “False” provided str data is a combination of str or digit with special
symbols.
• Syntax:
Variable name = [Link]()
Example, 1: a="123ab"
b=[Link]()
print(b)
17 | P a g e
Output: True
Example, 2: a="abc123#@!"
b=[Link]()
print(b)
Output: False # This return “False” provided str data is a
combination of str or digit with special symbols.
➢ isalpha ():
• This function returns True provided str data must contain purely alphabets (a-z).
• Syntax:
Variable name = [Link]()
Example, 1:
a="abcd"
b=[Link]() # only purely alphabets then its provided True.
print(b)
Output: True
Example, 2:
a="abcd123@"
b=[Link]() # if alphanumeric and special symbols then
results gets false.
print(b)
Output: False
➢ isdigit ():
• This function returns True provided str data must contain purely digits (0-9).
• Syntax:
Variable name = [Link]()
Example, 1:
a="1233"
b=[Link]() #This function returns ‘True’ provided str data
must contain purely digits (0-9).
print(b)
Output: True
Example, 2:
18 | P a g e
a="djfhedf658"
b=[Link]()
print(b)
Output: False
➢ isspace ():
• This function returns True provided str data must contain purely spaces (“ “).
• Syntax:
Variable name = [Link]()
➢ islower ():
• This function returns True provided string data must contain purely lowercase (a-
z).
• Syntax:
Variable name = [Link]()
Example, 1: a="lowercase"
print([Link]())
Output: True
Example, 2: a="Kumar"
print([Link]())
Output: False
➢ isupper ():
• This function returns True provided string data must contain purely uppercase (A-
Z).
19 | P a g e
• Syntax:
Variable name = [Link]()
Example, 1: a="UPPERCASELETTER"
print([Link]())
Output: True
Example, 2: a="upperCASE"
print([Link]())
Output: False
➢ lower ():
• This function converts uppercase data into lowercase.
• Syntax:
Strobj1 = [Link]()
Example: a="KUMAR"
b=[Link]() #This function converts uppercase data into lowercase.
print(b)
Output: kumar
➢ upper ():
• This function converts lowercase data into uppercase.
• Syntax:
Strobj1 = [Link]()
Example: a="barak obama"
b=[Link]()
print(b)
Output: BARAK OBAMA
➢ bytes ():
• This data type is used for storing sequence of numerical integer value ranges 0 –
256.
• To represent the elements of bytes data type we don’t have any symbolic notation,
but we can convert other data types of elements into bytes type by using “bytes()”.
• Syntax:
listobj2 = bytes(listobj1)
20 | P a g e
Example: a=10
b=bytes(a)
print(b,type(b))
21 | P a g e
COLLECTION OF DATA TYPE
A. LIST IN PYTHON:
• A list is a container that stores items of different data types (ints, floats, Boolean,
strings, etc.) in an ordered sequence.
• Purpose of this data type is that to store multiple values either same type or different
type or both types with unique and duplication value.
• Lists are used to store multiple items in a single variable.
• The element of list mostly written in square braces [] and element separated by comma
(,).
• Syntax:
Listobj = [list of values / elements separated by comma]
• List order maintain insertion order.
• List object belong to mutable.
22 | P a g e
• On list object we can perform both indexing and slicing operation.
OPERATION OF LIST:
Python Indexing a list: -
• The list index() method helps you to find the first lowest index of the given element.
• If there are duplicate elements inside the list, the first index of the element is returned.
• Syntax:
[Link](element)
Example, 1:
a=["python","c++","java","php","c#",".Net","javascript"]
print("MY LIST IS: ", a)
# find out the index value of “php” in given list....
print("The Index value of “php” is:", [Link]("php"))
# find out the index value of javascript in given list....
print("The index value of javascript is :", [Link]("javascript"))
Output:
MY LIST IS: ['python', 'c++', 'java', 'php', 'c#', '.Net', 'javascript']
The Index value of “php” is: 3
The index value of javascript is: 6
Slicing a List: -
• With this operator you can specify where to start the slicing, where to end and specify
the step.
• If L is a list, the expression L [start: stop: step] returns the portion of the list from
index start to index stop, at a step size step.
• Syntax:
listobj [Begin: End: Step]
Example:
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print("My list is:", a)
# slicing a list from 1 to 6 elements....
print("Slicing of 1 to 6 elements from list is:", a[1:6])
Output:
My list is: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
23 | P a g e
Slicing of 1 to 6 elements from list is: ['b', 'c', 'd', 'e', 'f']
Syntax 1:
listobj [begin: end]
• This syntax given range of character from Begin Index to End – 1 Index provided.
[Begin < End otherwise we never get any result].
Syntax 2:
listobj [Begin:]
• In this syntax we didn’t specify the end index in that PVM take overall list object length
as end index.
Syntax 3:
listobj [: End]
• In this syntax we didn’t specify begin index then PVM takes initial index as begin index.
• Positive or negative for end index it will take n-1 value.
Syntax 4:
listobj [Begin: End: Step]
Example: a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print("My list is:", a)
# slicing a list from 1 to 6 elements....
print("Slicing of 1 to 6 elements from list is:", a[1:6])
# slicing a list from -4 elements....
print("Slicing of -4 elements is:", a[-4:])
# slicing a list of elements....
print("Slicing a list of elements is:", a[:-5])
# slicing a list of elements by using [begin : end : step]....
print("Slicing a list of elements is:", a[1:7:2])
# reverse a list of elements by using [ : : -1]
print("Reverse a list of elements:", a[ : :-1])
Output:
24 | P a g e
My list is: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
Slicing of 1 to 6 elements from list is: ['b', 'c', 'd', 'e', 'f']
Reverse a list of elements: ['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
Python has many useful list methods that makes it really easy to work with lists. Here
are some of the commonly used list methods.
Methods Descriptions
➢ append():
• The append() method adds an item to the end of the list.
• The method takes a single argument
Item - an item (number, string, list etc.) to be added at the end of the list.
• Syntax:
[Link](item/element)
Example:
25 | P a g e
a = ['Dollar', 'Euro', 'Pound']
# append 'Rupees' to the list….
[Link]('Rupees')
print(a)
Output: ['Dollar', 'Euro', 'Pound', 'Rupees']
➢ insert(): -
• The insert() method inserts an element to the list at the specified index.
• The insert() method takes two parameters:
• index - the index where the element needs to be inserted
• element - this is the element to be inserted in the list
Notes:
• If index is 0, the element is inserted at the beginning of the list.
• If index is 3, the index of the inserted element will be 3 (4th element in the list).
• Syntax: -
[Link](index, element)
➢ clear(): -
• The clear() method removes all items from the list.
• The clear() method doesn't take any parameters.
• Syntax:
[Link]()
➢ remove(): -
• The remove() method removes the first matching element (which is passed as an
argument) from the list.
• The remove() method takes a single element as an argument and removes it from
the list.
• Syntax: -
[Link](element)
➢ pop(): -
• The pop() method removes the last element / item of the given list and returns the
removed element / item.
• Syntax: -
[Link]()
Example: # programming languages list:
languages = ['Python', 'Java', 'C++', 'French', 'C']
# remove the value:
L= [Link]()
print('Return Value:', L)
# Updated List:
print('Updated List:', languages)
Output: Return Value: C
Updated List: ['Python', 'Java', 'C++', 'French']
27 | P a g e
➢ pop(index): -
• The pop(index) method removes the item at the given index from the list and returns
the removed item.
• Syntax: -
[Link](index value)
Example:
# programming languages list…
languages = ['Python', 'Java', 'C++', 'French', 'C']
# remove and return the 4th item
L = [Link](3)
print('Return Value:', L)
# Updated List
print('Updated List:', languages)
Output:
Return Value: French
Updated List: ['Python', 'Java', 'C++', 'C']
➢ count(): -
• The count() method returns the number of times the specified element appears in
the list.
• This function is used for counting number of occurrences of specific elements.
• If the specific elements don’t exist then we get ‘0’ occurrence.
• The count() method takes a single argument:
• element - the element to be counted.
• The count() method returns the number of times element appears in the list.
• Syntax: -
[Link](element)
Example:
# create a list…..
a = [2, 3, 5, 2, 11, 2, 7]
# check the count of 2…..
count = [Link](2)
print('Count of 2:', count)
Output: Count of 2: 3
28 | P a g e
➢ index(): -
• The index() method returns the index of the specified element in the list.
• Tis function is used to finding index of the specified element first occurrence of the
list.
• Syntax: -
[Link](element / item)
Example:
a = ['cat', 'dog', 'rabbit', 'horse']
# get the index of 'dog'.
b = [Link]('dog')
print(b)
Output: 1
➢ reverse(): -
• The reverse() method reverses the elements of the list.
• Obtaining the reverse order of list.
• Syntax: -
[Link]()
Example:
➢ copy(): -
• The copy() method returns a shallow copy of the list.
• The copy() method returns a new list. It doesn't modify the original list.
• Syntax: -
29 | P a g e
newlist = [Link]()
Example:
# mixed list.
a = [2, 3, 5]
# copying a list
b = [Link]()
print('Copied List:', b)
Output: Copied List: [2, 3, 5]
➢ sort():
• This function is used for obtaining sorting of elements of list.
• Syntax: -
[Link]()
• Ascending order.
Example:
a = [7,8,9,6,5,4,2,3,1]
print(a)
[Link]()
print(a)
Output:
[7, 8, 9, 6, 5, 4, 2, 3, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
➢ extend():
• This functionality is used for extending the functionality of source list object from
destination list object one at a time.
• Syntax:
[Link](destination list)
Or
[l1=l1+l2] #just remember for simple way.
Example:
kkr = [10, "kumar"]
print(kkr)
kk = ["b. tech", "sppu"]
30 | P a g e
print(kk)
[Link](kk)
print(kkr)
Output:
[10, 'kumar']
['b. tech', 'sppu']
[10, 'kumar', 'b. tech', 'sppu']
➢ copy():
1. shallow copy().
• Initially contents of both of the objects are same.
• Both the memory address of the objects is different.
• To implements shallow copy in python we use copy().
• Both the object modification is independent.
• If we do the modification on one object then they are not reflected into other objects
because both the objects are pointing different add.
• Syntax:
[Link]()
Example:
l1=[10,"kkr","python"]
print(l1,id(l1))
l2=[Link]()
print(l2,id(l2))
Output: [10, 'kkr', 'python'] 1582950176192
[10, 'kkr', 'python'] 1582950131840
2. deep copy():
• Initial content of both of the object is same.
• Both the memory address of both the objects are same.
• Both the object modification is dependent.
• If we do the modification on one object then they are reflected into other objects
because both the objects are pointing same add.
31 | P a g e
• Syntax:
listobj1=listobj2
Example:
l1=[10,"cool"]
print(l1,id(l1))
l2=l1 #deep copy
print(l2,id(l2))
Output:
[10, 'cool'] 1582950184896
[10, 'cool'] 1582950184896
➢ nested() list:
• It is also called inner list.
• The process of defining one list in another is called nested list.
• Syntax:
listobj = [Val1, Val2,…..[Val11, Val12,…], [Val21, Val22],…… Val-n]
• Here- [Val11, Val12] = is one inner list
• [Val21, Val22] = is another list.
Example: I want to store number, name, enter the marks (3 sub), external marks of (3
sub) and college name.
32 | P a g e
B. TUPLE IN PYTHON:
• The purpose of this data type is to store multiple value either of same type or different
types or both types with unique and duplicate value.
• The element of tuple must be written in braces () and elements separated by comma “,
“.
• Syntax:
tupleobj = (list of value / element separated by comma)
• Tuple object maintain insertion order.
• It belongs to immutable.
• On tuple we can perform indexing and slicing.
• To covert one type of value into tuple we can use tuple() function.
Tupleobj = ()
Tupleobj = tuple()
t1 = ()
t2 = tuple()
Notes:
• The functionality of tuple is exactly similar to list but an object of tuple belongs to
immutable & object of list belong to mutable.
➢ Additional function in tuple:
1. Count()
2. Index()
➢ Not available function in tuple:
Append(), Clear(), Insert(), Remove(),
33 | P a g e
• IMMUTABLE OBJECTS: These are of in-built types like int, float, bool, string,
unicode, tuple, Frozen Set. In simple words, an immutable object can’t be changed
after it is created.
• MUTABLE OBJECTS: These are of type list, dict, set. Custom classes are generally
mutable.
S. No List Tuple
1 Lists are mutable. Tuples are immutable.
2 Iteration in lists is time consuming. Iteration in tuples is faster
3 Lists are better for insertion and Tuples are appropriate for accessing
deletion operations the elements
4 Lists consume more memory Tuples consume lesser memory
5 Lists have several built-in methods Tuples have comparatively lesser built-
in methods.
6 Lists are more prone to unexpected Tuples operations are safe and chances
errors of error are very less
7 Creating a list is slower because two Creating a tuple is faster than creating a
memory blocks need to be accessed. list.
C. SET IN PYTHON:
• The purpose of this data is that “to store multiple values either of same type or
different type or both type with unique values.”
• To convert one type of value into set type we use set() function.
34 | P a g e
• Set is an unordered collection of items.
• Where every element is unique and immutable.
• However, the set itself is mutable.
• Set data must be written in “{}” braces and element must be separated by “, “comma.
• An object of set does not maintain insertion order.
• On the object of set, we can’t perform both indexing and slicing because it can’t
maintain insertion order.
• Set object belong to both immutable and mutable.
• Set object belong to immutable in the case of item assignment and mutable in the case
of add() function.
• Syntax:
setobj = {val1, val2, ……, valn}
• Syntax for Empty set:
setobj = set()
Example, 1: a = {1, 2, 3, 2.5, "kaustubh", True}
print(a,type(a))
Output: {1, 2.5, 3, 2, 'kaustubh'} <class 'set'>
Items in list can be replaced Items in set cannot be Items in tuple cannot be
or changed changed or replaced changed or replaced
35 | P a g e
Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new
set
difference_update() Removes all elements of another set from this set
discard() Removes an element from the set if it is a member.
(Do nothing if the element is not in set)
intersection() Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and
another
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
pop() Removes and returns an arbitrary set element.
Raises KeyError if the set is empty
remove() Removes an element from the set. If the element is
not a member, raises a KeyError
symmetric_difference() Returns the symmetric difference of two sets as a
new set
symmetric_difference_update() Updates a set with the symmetric difference of
itself and another
union() Returns the union of sets in a new set
update() Updates the set with the union of itself and others
➢ add():
• This function is used for adding an element in set object.
• Syntax:
[Link](element)
Example:
s1={10, "python"}
print(s1,type(s1))
36 | P a g e
[Link]("java")
print(s1)
Output:
{'python', 10} <class 'set'>
{'python', 10, 'java'}
➢ clear():
• This function is used for removed all element of the set object.
• In short, clear() method is to clear the all element in the set object.
• Syntax:
[Link]()
Example:
s1 = {10, "python"} #set creation.
print(s1,type(s1))
[Link]() #clear operation.
print(s1) #after operation performing
printing the set object.
Output: {'python', 10} <class 'set'>
set()
➢ remove():
• This function is used for removing the specific element from set object.
• If the element doesn’t exist in the set object, then we get “Key Error”.
• Syntax:
[Link](element)
Example:
s1={10, "python", "kumar", 789456123, 14.35, 156+9j, True}
print(s1,type(s1))
[Link](14.35) #remove operation.
print(s1) #after operation performing printing the set object.
Output:
{True, 'kumar', 'python', 10, 789456123, (156+9j), 14.35} <class 'set'>
{True, 'kumar', 'python', 10, 789456123, (156+9j)}
➢ discard():
• This function is used for removing the element from set object.
37 | P a g e
Note: If the element doesn’t exist in the set object it never removes and no error at runtime.
• Syntax:
[Link](element)
Example:
➢ pop():
• In this function is used for removing any arbitrary element from set object.
Note: When we call this function upon empty set object then we get “Key Error”.
• Syntax:
[Link]()
Example:
➢ copy():
• It’s used to copy the content of one object into another object (implements of shallow
copy.)
• Syntax:
setobj2=[Link]()
38 | P a g e
Example:
s1={10, "python", "kumar", 789456123, 14.35, 156+9j, True}
print(s1,id(s1))
s2=[Link]() #copy operation.
print(s2,id(s2)) #after operation performing printing the set object.
Output:
{True, 'kumar', 'python', 10, 789456123, (156+9j), 14.35} 1616054226496
{True, 'kumar', 'python', 10, 789456123, (156+9j), 14.35} 1616055286240
➢ isdisjoint():
• The isdisjoint() method returns True if none of the items are present in both sets,
otherwise it returns False.
• In simple words, they do not have any common element in between them.
• This function return True provided both sets does not contain common elements.
• Syntax:
[Link](setobj2)
Example:
s1 = {10, 20, 30, 40, 50}
s2 = {60, 70, 80}
[Link](s2)
Output: True
➢ issuperset():
• This function returns True provide “set obj1” contain all the elements of set obj2
returns False.
• Syntax:
[Link](setobj2)
Example:
s0 = {1, 2, 3, 4}
s3 = {3, 4}
[Link](s3)
Output: True
39 | P a g e
➢ issubset():
• This function return True provided all the elements of set obj1 present in set obj2,
otherwise it returns False.
• The issubset() method returns True if all elements of a set are present in another
set. If not, it returns False.
• Syntax:
[Link](setobj1)
Example:
s1 = {10, 20, 30, 40}
s2 = {10, 20}
[Link](s2)
Output: False
➢ union ():
• This union() function returns a set that contains all items from the original set, and all
items from the specified set(s).
• The union() method returns a new set containing all items from all the specified sets,
with no duplicates.
• We can specify as many sets as we want, just separate each set with a comma (,).
• If we want to modify the original set instead of returning a new one, use update()
method.
• Syntax:
Setobj3 = [Link](setobj2)
Or
Setobj3 = [Link](setobj1)
Example:
s1 = {10, 20, 30, 40}
s2 = {20, 30, 40, "python", "java", "c++"}
print(s1)
print(s2)
s3=[Link](s2)
print(s3,type(s3))
40 | P a g e
Output: {40, 10, 20, 30}
{'python', 20, 40, 'c++', 'java', 30}
{'python', 40, 10, 'java', 20, 'c++', 30} <class 'set'>
➢ intersection():
• This is obtain all common elements of set obj1 and set obj2 and place them setobj3.
• The intersection() method returns a set that contains the similarity between two or
more sets.
• Syntax:
Setobj3 = [Link](setobj2)
Example:
s1 = {10, 20, 30, 40}
s2 = {20, 30, 40, "python", "java", "c++"}
[Link](s2)
Output: {20, 30, 40}
➢ difference():
• In this syntax, difference removes common elements from setobj1 & setobj2 and place
the remaining elements of setobj1 in setobj3.
• The function difference() returns a set that is the difference between two sets.
• Syntax:
Setobj3 = [Link](setobj2)
Or
setC = [Link](setB)
Example, 1:
s1 = {10, 20, 30, 40}
41 | P a g e
s2 = {20, 30, 40, "python", "java", "c++"}
[Link](s2)
Output: {10}
Example, 2:
[Link](s1)
Output: {'c++', 'java', 'python'}
➢ symentric_difference():
• The Python symmetric_difference() method returns the symmetric difference of two
sets.
• The symmetric difference of two sets A and B is the set of elements that are in either
A or B, but not in their intersection.
• which is equal to the elements present in either of the two sets, but not common to
both the sets.
➢ update():
• This function update / adds all the elements of set obj2 to set obj1.
42 | P a g e
• The update() method updates the original set by adding items from all the specified
sets, with no duplicates.
• We can specify as many sets as we want, just separate each set with a comma (,).
• If we don’t want to update the original set, use union() method.
• Syntax:
[Link](setobj2)
Or
[Link](set1,set2…)
Note: The functionality of frozen set () is exactly similar to set (), but frozen set object belongs
to immutable and object of set belongs to both.
• This data type is used to store mutable value either same or different or both type
with unique values.
43 | P a g e
• The element of frozen set can be obtained by converting other type collection
elements by using frozenset ().
• Syntax:
frozensetobj=frozenset ()
Example:
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
print(x)
Output: frozenset({'banana', 'apple', 'cherry'})
E. DICTIONARY IN PYTHON:
• Purpose: of this data type is to store data in the form of (key, values).
• In (key, value), the data is key represents unique and value may or may not be
unique.
• The elements of dict must be represented with curly braces {}.
• The left side of “:” is a key, and the right side is a value.
• The key should be unique and an immutable object. A number, string or tuple can
be used as key.
• If we use only any values for keys of string type then they must be enclosed within
single or double quote.
• An object of dictionary maintains insertion order because of key: value nature.
44 | P a g e
• On the object of dict we can’t apply indexing and slicing because of key and value
pair nature.
• The object of dict belong to mutable. And in the case of keys its immutable and values
are mutable.
• Syntax:
dictobj = {key: value}
Or
dictobj={key1:value1, key2:value2}
TYPE OF DICTIONARY:
1. Empty:
• Syntax:
dictobj = {}
Or
Dictobj = dict()
• Empty dict is one which does not contain any entries and whose length is ‘0’.
2. Non-Empty
• Syntax:
dictobj = {key1:value1, key2: value2…., key n: value n}
Example, 1: fruits = {"Mango": 600, "Apple": 300, "Watermelon": 80}
print(fruits, type(fruits))
45 | P a g e
BUILT-IN DICTIONARY METHODS:
Method Description
[Link]() Removes all the key-value pairs from the dictionary.
[Link]() Returns a shallow copy of the dictionary.
[Link]() Creates a new dictionary from the given iterable (string, list, set, tuple)
as keys and with the specified value.
[Link]() Returns the value of the specified key.
[Link]() Returns a dictionary view object that provides a dynamic view of
dictionary elements as a list of key-value pairs. This view object
changes when the dictionary changes.
[Link]() Returns a dictionary view object that contains the list of keys of the
dictionary.
[Link]() Removes the key and return its value. If a key does not exist in the
dictionary, then returns the default value if specified, else throws a
KeyError.
[Link]() Removes and return a tuple of (key, value) pair from the dictionary.
Pairs are returned in Last In First Out (LIFO) order.
[Link]() Returns the value of the specified key in the dictionary. If the key not
found, then it adds the key with the specified default value. If the
default value is not specified then it set None value.
[Link]() Updates the dictionary with the key-value pairs from another
dictionary or another iterable such as tuple having key-value pairs.
[Link]() Returns the dictionary view object that provides a dynamic view of all
the values in the dictionary. This view object changes when the
dictionary changes.
➢ Clear():
• This is used for removing all elements / entries of the dict object.
• Syntax:
[Link]()
Example:
a = {"mahindra" : "xuv700", "maruti" : "ciaz", "hyundai" : "i20_sports"}
print(a,type(a))
46 | P a g e
#apply clear operation.
[Link]()
print(a)
Output:
{'mahindra': 'xuv700', 'maruti': 'ciaz', 'hyundai': 'i20_sports'} <class 'dict'>
{}
➢ copy():
• Its used for copying the content of one dict object to another dict object .
(Implementing shallow copy).
• Syntax:
dictobj2 = [Link]()
Example:
a = {"mahindra": "xuv700", "maruti": "ciaz", "hyundai" : "i20_sports"}
print(a,id(a))
b = [Link]()
print(b,id(a))
Output:
{'mahindra': 'xuv700', 'maruti': 'ciaz', 'hyundai': 'i20_sports'} 2057241371200
{'mahindra': 'xuv700', 'maruti': 'ciaz', 'hyundai': 'i20_sports'} 2057241371200
➢ get():
• This function is used obtaining the data of value by passing of key.
• If the value of is present it returns the correspondents value, otherwise it written none.
• Syntax:
Variable name = [Link](key)
Example, 1:
d1 = {10: "apple", 20: "mango"}
val = [Link](10)
print(val, type(val))
Output: apple <class 'str'>
Example, 2:
d1 = {10: "apple", 20: "mango"}
val =[Link](30)
print(val, type(val))
47 | P a g e
Output: None <class 'None Type'>
➢ pop():
• Its used for remaining (key: value) from dict object provided key presented in dict
object otherwise we get “KeyError”.
• Syntax:
[Link](key)
Example:
d1 = {10: "apple", 20: "mango", "mahindra": "xuv700", "maruti": "ciaz"}
[Link]("maruti")
print(d1,type(d1))
Output:
{10: 'apple', 20: 'mango', 'mahindra': 'xuv700'} <class 'dict'>
➢ popitem():
• It is used to removing and returning last entry of dictionary object.
• If we perform this on empty dict then we get Key Error.
• Syntax:
[Link]()
Output: ('V', 5)
('IV', 4)
('III', 3)
('II', 2)
('I', 1)
➢ keys():
• It is used to obtaining set of keys in the form of object.
48 | P a g e
• Syntax:
Variable name = [Link]()
Example:
d1 = {'name': 'raj', 'age': 21, 'marks': 62, 'course': 'Computer Engg'}
[Link]()
Output: dict_keys(['name', 'age', 'marks', 'course'])
➢ values():
• It is used to obtaining set of values in the form of object.
• Syntax:
Variable name = [Link]()
Example:
romanNums = {'I':1,'II':2,'III':3,'IV':4,'V':5, 'VI':6}
[Link]()
Output: dict_values([1, 2, 3, 4, 5, 6])
➢ items():
• This function is used to obtaining set of (key, value) entries in the form of
object.
• Syntax:
variable name = [Link]()
Example:
romanNums = {'I':1,'II':2,'III':3,'IV':4}
d = [Link]() #items function is applying.
print(d)
Output: dict_items([('I', 1), ('II', 2), ('III', 3), ('IV', 4)])
➢ update():
• This function the dict obj1 values with dict obj2 values.
• Syntax:
[Link](dictobj2
Example:
person = {'name': 'KUMAR', 'age': 22}
prof = {'salary': 20000, 'car_used': 'baleno'}
[Link](prof)
49 | P a g e
print(person)
Output: {'name': 'KUMAR', 'age': 22, 'salary': 20000, 'car_used': 'baleno'}
➢ None Type:
• None is keyword act as value.
• The value of “None” is not false, space, empty, 0.
• Syntax:
Variable = None
Example:
x = None
print(x, type(x))
Output: None <class 'NoneType'>
WHAT IS PROGRAM?
Note: It’s not recommended to use interactive mode for big problem-solving
statement.
50 | P a g e
Python [Link] Or py [Link]
Example: Pycharm, Spider, VS. Code, Editplus, Python IDE Shell, Jupyter.
Example, 1: a = 20
print(“value of a is =”, a)
• Syntax, 4:
print(value cum message with format())
Example:
a = 10
b = 20
c = a+b
print("value of a ={}".format(a))
print("value of b ={}".format(b))
print("sum of a and b is ={}".format(c))
Output: value of a =10
value of b =20
sum of a and b is =30
51 | P a g e
➢ Program for accepting two values from bey board multiply.
Example, 1:
a = int(input("Enter 1st value:"))
b =int(input("Enter 2nd value:"))
print("multiply({},{}) is = {}".format(a,b,a*b))
Output:
Enter 1st value:45
Enter 2nd value:78
multiply(45,78) is = 3510
Example, 2
num1=int(input("1st value:"))
num2=int(input("2nd value:"))
print("division of ({},{}) = {}".format(num1,num2,num1//num2))
Output:
1st value:14
2nd value:2
division of (14,2) = 7
TASK: Examples:
52 | P a g e
area = 0.5 * l * h
print("Area of triangle:", area)
OPERATORS IN PYTHON
WHAT IS OPERATOR?
53 | P a g e
✓ Python Assignment Operator
✓ Python Logical Operator
✓ Python Membership Operator
✓ Python Identity Operator
✓ Python Bitwise Operator
1) Arithmetic Operator:
• Arithmetic operators are used to performing mathematical operations like addition,
subtraction, multiplication, and division.
2) Assignment Operator:
• Purpose of this operator is that to transfer RHS / Expression value to left hand side
variable.
• Symbol: =
• We can use assignment operator in two ways:
1. Single value assignment:
• Syntax: LHS = RHS
Example: a = 10
Print(a)
Example: a, b, c = 10,20,30
print(a, b, c)
54 | P a g e
3) Relational Operator:
• Purpose of this operator is that “to compare two values”.
• If two or more objects or variable connected with relational operator then it’s
called Relational Expression.
• Relational expression is also called Condition and they are evaluated either True
or False.
• In python there are 6 types of operators are available.
4) Logical operator:
• This operator is used for combining two or more relational expression.
• If two or more relational expression are combined with logical operator then it called
logical expression or compound condition and it’s evaluated either to be True or
False.
• In Python, Logical operators are used on conditional statements (either True or False).
They perform Logical AND, Logical OR and Logical NOT operations.
55 | P a g e
✓ Or Operator:
• If first relational expression is “True” and hence the entire result logical expression
is “True”.
✓ And Operator:
✓ Not Operator:
Expression Output
False True
True False
5) Bitwise operator:
• Integer data: this operator operate on integer data in the form of bit by bit.
• Bitwise complement operator (~).
• We have total 6 bitwise operators:
56 | P a g e
a) Bitwise Left Shift (<<):
• Syntax:
• This operator shifts the no. of bits towards left and place zero in the empty
places of right shift side.
Output: 80
0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
0 0 0 0 0 0 0 0 0 1 0 1 0 x x x
• This operator shifts the no. of bits towards right and place zero in the empty
places of left shift side.
• Formula for bitwise right shift operator:
Output: 1
For Example: 10 / 23 = 10 / 8 = 1
c) Bitwise OR operator:
Example:
a = {10, 20, 30, 40, 50}
57 | P a g e
b = {40, 50, 60, 70, 80, 90, 100, 110}
print(a|b)
Output: {100, 70, 40, 10, 110, 80, 50, 20, 90, 60, 30}
Example:
a = {10, 20, 30, 40, 50}
b = {40, 50, 60, 70, 80, 90, 100, 110}
print(a|b)
Output: {40, 50}
Example, 1:
a = 19 ^ 21
print(a)
Output: 6
Example, 2:
result = True ^ False
print(result)
Output: True
58 | P a g e
print(result)
Output: False
Example, 5: Let’s see how to swap integers without a temporary variable using XOR.
a = 21
b = 19
print('The value of a is: ', a)
print('The value of b is: ', b)
a =a^b
b = b^a
a = a^b
print('After swapping: ')
print('The value of a is: ', a)
print('The value of b is: ', b)
Output:
The value of a is: 21
The value of b is: 19
After swapping:
The value of a is: 19
The value of b is: 21
Res = ~ value
6) Membership Operator:
• This operator is related to the iterable object (e.g. string, tuple, set, dict)
• This operator checks the exitance of particular value in iterable object.
59 | P a g e
• We have two types of membership operator: a) in, b) not in.
a) in:
• Syntax: value in iterable object
• “in” operator returns True provided “value” presented in the iterable object and
returns False if the “value” is not present.
b) not in:
• Syntax: value not in iterable object
• “not in” operator returns True provided “value” presented in the iterable object
and returns False if the “value” is not present.
Example:
#not in operator working
list1= [1,2,3,4,5]
string1= "My name is Kaustubh"
tuple1=(11,22,33,44)
print(5 not in list1) #False
print("is" not in string1) #False
print(88 not in tuple1) #True
Output:
False
False
True
60 | P a g e
7) Identity Operator:
• Purpose to compare memory address of two object.
is not Returns True if both variables are not the same object x is not y
a) is:
• Syntax: variable1 is variable2
• “is” operator return True provided var1 and var2 contain same memory address
otherwise return False.
Example: a=5
b=5
print(a is b)
Output: True
b) is not:
• Syntax: variable1 is not variable2
• “is not” operator return True provided var1 and var2 contain different memory
address otherwise return False.
Example:
d1 = {10, 20, 30}
d2 = {10, 20, 30}
print(d1, id(d1))
print(d2, id(d2))
print(d1 is d2)
print(d1 is not d2)
Output:
{10, 20, 30} 2161176844992
{10, 20, 30} 2161176845216
False
True
61 | P a g e
CONTROL FLOW STATEMENTS IN PYTHON
Purpose of this to perform some operation (x-operation and y-operation) only once depend on
condition.
There is total 3 type of flow control statements:
I. Conditional / Selection statement
II. Looping / Iterative statements
III. Misc flow control statements
• In Python, the selection statements are also known as Decision control statements or
branching statements.
• The selection statement allows a program to test several conditions and execute
instructions based on which condition is true.
62 | P a g e
• Some Decision Control Statements are:
a) simple if
b) if-else
c) nested if
d) if-elif-else
➢ simple if:
• If statements are control flow statements that help us to run a particular code, but only
when a certain condition is met or satisfied.
• A simple if only has one condition to check.
• Here, the program evaluates the test expression and will execute statement(s) only if
the test expression is True.
• If the test expression is False, the statement(s) is not executed.
• In Python, the body of the if statement is indicated by the indentation. The body
starts with an indentation and the first unindented line marks the end.
• Python interprets non-zero values as True. None and 0 are interpreted as False.
• Syntax:
if test expression:
statement(s)
63 | P a g e
Example, 1:
n = 10
if n % 2 == 0:
print("n is an even number")
Output: n is an even number
Example, 2:
# If the number is positive or negative, we print an appropriate message
num = int(input("Enter the any number :"))
if(num > 0):
print(num, "is a positive number.")
if(num<0):
print(num, "is a negative number")
➢ if-else:
• The if...else statement evaluates test expression and will execute the body of if only
when the test condition is True.
• If the condition is False, the body of else is executed.
• Indentation is used to separate the blocks.
• Syntax:
if test expression:
Body of if
else:
Body of else
64 | P a g e
Example:
password = input('Enter password ')
if password == "kaustubh123":
print("Correct password")
else:
print("Incorrect Password")
65 | P a g e
elif test expression:
Body of elif
else:
Body of else
Example:
x = 15
y = 12
if x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than y")
➢ Nested if:
• We can have an if...elif...else statement inside another if...elif...else statement. This is
called nesting in computer programming.
• Any number of these statements can be nested inside one another.
66 | P a g e
• Indentation is the only way to figure out the level of nesting. They can get confusing,
so they must be avoided unless necessary.
• Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example:
a = 40
b = 80
c = 70
if(a>b):
if(a>c):
print("a is greater")
if(b>a):
if(b>c):
print("b is greatest")
if(c>a):
if(c>b):
67 | P a g e
print("c is greatest")
Output: b is greatest
Example, 2:
# Python program to demonstrate
# nested if statement
num = 15
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
68 | P a g e
A. WHILE STATEMENT:
• Python While Loop is used to execute a block of statements repeatedly until a given
condition is satisfied.
• And when the condition becomes false, the line immediately after the loop in the
program is executed.
• While loop falls under the category of indefinite iteration.
• Indefinite iteration means that the number of times the loop is executed isn’t
specified explicitly in advance.
• Syntax:
while test_expression:
Body of while
Example:
i=1
while i < 4:
print(i)
i += 1
Output: 1
2
3
69 | P a g e
While loop with else:
• In Python, the else clause can be used with a while statement. The else block is gets
executed whenever the condition of the while statement is evaluated too false.
• But if the while loop is terminated with break statement, then else doesn't execute.
• Here “while” and “else” are the keywords.
• Here the test condition is True, then execute block statement
• And once again evaluate test condition.
• And if test condition is True, and again block statement of this process will be
repeated for finite number of times.
• If test condition is False, then execute else block of statement.
• Else block is option.
• Syntax:
While (test condition):
Statement 1
Statement 2
else:
else block statement
Other statements
70 | P a g e
i += 1
else:
print("i is no longer less than 4")
Output: 1
2
3
i is no longer less than 4
B. FOR STATEMENT:
• The execution behaviour of for loop is that each element of iterable object keep in
variable name.
• Execute block of statements until all elements of iterable object completed.
• In Python, the for loop is used to iterate over a sequence such as a list, string, tuple, other
iterable objects such as range.
• Here val is the variable that takes the values if the item inside the sequence on each
iteration.
• Syntax:
for val in sequence:
loop body
Or
for i in range/sequence:
statement 1
statement 2
71 | P a g e
statement n
Example:
# Iterate through a list
colors = ['red', 'green', 'blue', 'yellow']
for x in colors:
print(x)
Output: red
green
blue
yellow
Example, 1:
colors = ['red', 'green', 'blue', 'yellow']
for x in colors:
print(x)
else:
print('Done!')
Output: red
green
72 | P a g e
blue
yellow
Done!
73 | P a g e
for loop with range():
• The range() function returns a sequence of numbers starting from 0 (by default) if
the initial limit is not specified and it increments by 1 (by default) until a final limit is
reached.
• The range() function is used with a loop to specify the range (how many times) the
code block will be executed.
Example, 1:
# Print 'Hello!' three times
for x in range(3):
print('Hello!')
Output: Hello!
Hello!
Hello!
Example, 2:
#Program to iterate through a list using range()
city = ['London', 'Paris', 'Mumbai', 'Sydney', 'California']
size = len(city)
#iterating over the list using the range() function
for x in range(size):
print("I Love", city[x])
Output:
I Love London
I Love Paris
I Love Mumbai
I Love Sydney
I Love California
Reverse for loop:
Sometimes we require to do reverse looping, which is quite useful. For example, to
reverse a list. There are three ways to iterating the for loop backward
• Reverse for loop using range()
• Reverse for loop using the reversed() function
✓ Backward Iteration using the reversed() function:
74 | P a g e
• We can use the built-in function reversed() with for loop to change the order of
elements, and this is the simplest way to perform a reverse looping.
Example:
# Reversed numbers using reversed() function
list1 = [10, 20, 30, 40]
for num in reversed(list1):
print(num)
Output: 40
30
20
10
✓ Reverse for loop using range():
• We can use the built-in function range() with the for loop to reverse the elements’
order.
• The range() generates the integer numbers between the given start integer to the
stop integer.
Example:
print("Reverse numbers using for loop")
num = 5
# start = 5
# stop = -1
# step = -1
for num in (range(num, -1, -1)):
print(num)
Output: 4
3
2
1
0
75 | P a g e
Output: 4
3
2
1
76 | P a g e
Nested for loop
77 | P a g e
Key Points to Remember:
• List comprehension is an elegant way to define and create lists based on existing
lists.
• List comprehension is generally more compact and faster than normal functions
and loops for creating list.
• However, we should avoid writing very long list comprehensions in one line to ensure
that code is user-friendly.
• Remember, every list comprehension can be rewritten in for loop, but every for loop
can’t be rewritten in the form of list comprehension.
• Syntax:
newList = [expression(element) for element in oldList if condition]
Or
List = [int(val) for val in input().split()]
Example,1: Create List of Even Numbers without List Comprehension.
even_nums = [ ]
for x in range(21):
if x%2 == 0:
even_nums.append(x)
print(even_nums)
Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
The same result can be easily achieved using a list comprehension technique shown below.
Example: Create List of Even Numbers with List Comprehension.
even_nums = [x for x in range(21) if x%2 == 0]
print(even_nums)
Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
List comprehension works with string lists also. The following creates a new list of strings
that contains 'a'.
Example: List Comprehension with String List.
names = ['Steve', 'Bill', 'Ram', 'Mohan', 'Abdul']
names2 = [s for s in names if 'a' in s]
print(names2)
Output: ['Ram', 'Mohan']
78 | P a g e
Example 1: Iterating through a string Using for Loop.
h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters)
Output: ['h', 'u', 'm', 'a', 'n']
Let’s see how the above program can be written using list comprehensions.
Example 2: Iterating through a string Using List Comprehension.
h_letters = [ letter for letter in 'human' ]
print( h_letters)
79 | P a g e
FUNCTIONAL PROGRAMMING IN PYTHON
DEFINING FUNCTION
❖ Types of language:
• The purpose of function concept is that to perform certain operation and provided
code reusability.
➢ Un-structured Programming Language:
• In this language we don’t have function so that we can’t get code reusability.
• Limitation of un-structured programming language.
1. Development time more.
2. Memory space more.
3. Execution time is more.
4. Duplication.
80 | P a g e
5. Performance degraded.
➢ Structured Programming Language:
• In this language we use function so that reusability is available.
1. Development time less.
2. Memory space less.
3. Execution time is less.
4. Duplication is minimised.
5. Performance enhanced.
Ex.: C, Cpp, Java, Python, .Net.
❖ Introduction to function:
• The purpose of this concept is to provide code reusability.
❖ Definition of function:
• Sub program of main program is called function. Or A part of main program is
called function.
❖ Types of function:
• We have two types of functions:
A. Predefined Function / Built in function:
• Function which are already defined in python software and they are used by
programmer for performing universal operation.
Ex.: print(), id(), type(), len().
81 | P a g e
• Syntax:
def function_name (list of formal parameters):
docstring
statement 1
statement 2
statement n
❖ Parameter:
• parameters are always used in function definition.
82 | P a g e
• Two types of parameters:
a) Formal parameter:
• Formal parameter / variable used in function heading and they are used for
storing input values coming from function calls.
Example:
def addition(a, b): #formal parameters.
c=a+b #local variable..
return c
#main function..
x = int(input("Enter the first value:"))
y = int(input("Enter the second value:"))
c=addition(x, y)
print("Sum in main program={}".format(c))
b) Local parameter:
• Local parameter / variables used in function body and they used for storing
temporary result.
Example:
def addition():
x1 = int(input("Enter the any value: "))
x2 = int(input("Enter the any value: "))
x3 = x1 + x2
print("Sum of {} and {} = {}".format(x1,x2,x3))
addition()
Output: Enter the any value: 20
Enter the any value: 10
Sum of 20 and 10 = 30
Note:
• The values of formal and local parameters / variables can access within
corresponding function definition not in another context.
83 | P a g e
❖ Arguments:
• Arguments also called variable used in function call.
84 | P a g e
def function_name(param1, param2, param3=val1, paramn=val2 ):
:
:
• Here param3 and paramn are called default parameter.
Example:
#carinfo is function name.
def carinfo(company,model,price,tyre="Apollo"):
#print details of car info...
print("Company made :\t\t{}".format(company))
print("Car model : \t\t{}".format(model))
print("Car price :\t\t{}".format(price))
print("Car tyre preferred : \t{}".format(tyre))
#calls function...
carinfo('Mahindra’, ‘Thar 4x4', 14.50)
Output: Company made: Mahindra
Car model: Thar 4x4
Car price: 14.5
Car tyre preferred: Apollo
Rule:
• When we used default parameter in function definition, they must be used as last
parameter.
• Otherwise, we get error.
3) Keyword parameter argument:
• In some circumstances we know the function name and formal parameter names
and we don’t know the order of formal parameter names to pass the data / values
accurately we must use the concept of keyword parameter or argument.
• Syntax: for function definition
def function_name(parameter1, parameter2, …parametern):
:
:
• Syntax: for function calls
Function_name(paramn = valn1,param2 = val2, param1 = val2):
:
85 | P a g e
:
Example:
def team(name, project):
print(name, "is working on an", project)
team(project = "Edpresso.", name = 'FemCode')
86 | P a g e
Sub 3: 74
Student Name: RAJESH KUMAR
Total: 226
Rule:
• The *param must always written at last part of function heading and it must be one
(but not multiple).
• When we have variable length and default parameter in function heading, we use
default parameter as last and before we use variable length parameter.
87 | P a g e
scie: 45
Total: 86
Rule:
• The **param must always written at last part of function heading and it must be one
(but not multiple).
• When we have variable length and default parameter in function heading, we use
default parameter as last and before we use variable length parameter.
88 | P a g e
• Parameter list represents list of formal parameters used for holding the values
coming from function calls.
• Expression represents single executable statement and returns its value
automatically.
3. In this case the normal function returns In this case the lambda function
an integer. returns a function object.
4. The execution time of the program is The execution time of the program is
relatively slow compared to the lambda fast (0.00050 seconds).
function (0.001328 seconds)
5. Need more time to type the code This requires only 2 lines to add three
(requires 4 lines to do add three numbers.
numbers).
Example, 1:
big = lambda a, b: a if a>b else b
#main program
x1 = int(input("Enter first value = "))
x2 = int(input("Enter second value = "))
if (x1==x2):
print("Both values are equals.")
else:
print("Big number between ({}, {}) are = {}".format(x1,x2,big(x1,x2)))
89 | P a g e
Example, 2: Python program to find even and odd number using Lambda function.
nums = int(input("Enter the number here: "))
even_odd = lambda: "The given number is Even." if nums%2==0 nums==0
else "The given number is odd."
print(even_odd())
Output: Enter the number here: 78
The given number is Even.
• When we want MOFIDY the GLOBAL VARIABLE value inside of function then
global variable must be preceded with global keyword otherwise we get error.
90 | P a g e
return circumference
print("Area of given circle is :\t\t",area_of_the_circle(radius))
print("Diameter of given circle is :\t\t",diameter_of_circle(radius))
print("circumference of given circle is :\t",circumference_of_circle(radius))
print("-"*50)
Output: ---------------------------------------------------------------
Please enter the radius of given circle: 8
---------------------------------------------------------------
Area of given circle is: 200.96
Diameter of given circle is: 16.0
circumference of given circle is: 50.24
---------------------------------------------------------------
Example, 2: Local variable vs Global variable
total = 100 #global variable
def test(): # ”test” is function name.
marks = 19 #local variable
print("Marks: ", marks) #print local variable.
print("Total:”, total) #print global variable.
test() #calling function
Output: Marks: 19
Total: 100
❖ globals () function:
• When we come across same global variable name and local variable name in same
function definition. The PVM gives preference for local variable but not global
variable.
• In this context to extract the global variable names along with local variable names
we must use globals () and it returns an object of dict.
Example:
#globals() function
a=20
b=30
91 | P a g e
c=50 #here a,b,a are global variable
def calc():
global b, c #by using global keyword we did the modification
b=b+1
c=c+2
a=60
b=70
gv=globals()
res=a+b+gv['a']+gv['c'] #60+70+21+51
print("result=",res)
#main Program
print("inside of main program before the operation()=",a,b,a)
calc()
print("inside the main program after the operations()",a,b,a)
Output:
inside of main program before the operation()= 20 30 50
result= 202
inside the main program after the operations() 20 70 52
SPECIAL FUNCTION
92 | P a g e
• Purpose: To find out the iterable object by applying some function along with
certain condition.
• Syntax:
varname = filter(function_name, iterable_object)
• Here, name is an object of <class filter> and it converted into any collection type.
• Function name can be either normal function or anonymous function.
• Iterable object either sequence type or collection type.
• The execution process of filter () is each value of iterable object is sending to the
specified function. If the function returns True then the elements of iterable object
filtered. If the function returns False then the elements of iterable object will not
filtered.
Example, 1: Python code to people above 18 years old.
ages = [13, 90, 17, 59, 21, 60, 5]
adults = list(filter(lambda age: age>18, ages))
print(adults)
Output: [90, 59, 21, 60]
Example, 2: Python code to illustrate filter () with lambda ()
List1 = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(filter(lambda x: (x%2 != 0) , list1))
print(final_list)
Output: [5, 7, 97, 77, 23, 73, 61]
93 | P a g e
• The purpose of map () is that, “To obtain new collection object from existing
collection object by applying to a function with some processing logic.
• Syntax:
varname = map(function name, iterable object)
• The execution process of map () is that each value of iterable object’s is sending to
specified function, PVM executes the processing logic and returns the value (Not
True or False).
• Here, name is an object of <class map> and it converted into any collection type.
• Function name can be either normal function or anonymous function and it should
return some value (Not True or False).
Example, 1:
my_pets = ['dog', 'cat', 'parrot', 'lovebirds']
uppered_pets = list(map([Link], my_pets))
print(uppered_pets)
Output: ['DOG', 'CAT', 'PARROT', 'LOVEBIRDS']
Example, 2:
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
Output: [1, 4, 9, 16, 25]
• This function used to obtain single value / result from iterable object.
94 | P a g e
• Reduce () represent the in a predefined module called “functools”.
• Syntax:
varname = reduce(function_name, iterable_object)
Example, 1:
from functools import reduce
reduce(lambda a,b: a+b, [23,21,45,98])
Output: 187
Example, 2:
from functools import reduce
numbers = [3, 4, 6, 9, 34, 12]
def custom_sum(first, second):
return first + second
result = reduce(custom_sum, numbers)
print(result)
Output: 6
95 | P a g e
OBJECT ORIENTED PROGRAMMING
CLASS IN PYTHON:
• The purpose of classes concept is that “to develop programmer / user / custom defined
data typed to develop any real time application.
• The purpose of developing programmer defined data type is then to customize the
given problem.
• Syntax:
class <class_name>:
def instance-method-name (self, list of formal parameters if any):
:
Block of statements operations on objects
TYPES OF METHODS:
96 | P a g e
1. INSTANCE METHOD:
• Instance methods are used performing specified operations on the data of object
and hence instance methods are called object level methods.
• Instance method definition always takes “self” as first formal parameter which is
used for holding the reference / id of current object and hence “self” is called
implicit object. (But not keyword).
• Syntax:
class <class_name>:
def instance-method (self, list of formal parameters if any):
:
:
Specific instance data members
:
:
Block of statements operation on object
• Instance method must be called with respect to object name or self.
object_name.instance_method_name ()
Or
self.instance_method_name()
97 | P a g e
# Constructor
def __init__(self, name, age):
# Instance variable
[Link] = name
[Link] = age
# Instance method to access instance variable
def show(self):
print('Name:', [Link], 'Age:', [Link])
emma=Student("Jessa", 14)
[Link]()
98 | P a g e
def course(cls):
[Link]="Python"
def studata(self):
[Link]=input("Enter student name: ")
[Link]=input("Enter student standard: ")
[Link]=input("Enter student course name: ")
def showst(self):
print("\nStudent name: ",[Link])
print("Student standard: ",[Link])
print("Student course name: ",[Link])
[Link]()
my=Student()
[Link]()
[Link]()
Output:
Enter student name: RAJESH KUMAR
Enter student standard: XII
Enter student course name: Python
3. STATIC METHOD:
• This method is always we for performing universal operation of all types of
class.
• Static method definition must start with predefined decorator called
@staticmethod and it may or may not take any formal parameter.
• It cannot have cls or self-parameter.
• The static method cannot access the class attributes or the instance attributes.
• Syntax:
class<class_name>:
@staticmethod
def static-method name(list of formal parameter if any):
:
99 | P a g e
Block of statement utility universal operation.
• Static must be called with respect to class_name or object_name of
corresponding class where static method present.
Class_name.staticmethod_name()
Or
Object_name.staticmethod_name()
Example:
class Music:
@staticmethod
def play():
print("*Playing music*")
def stop():
print("stop playing")
[Link]()
[Link]()
Output: *Playing music*
stop playing
CONSTRUCTOR IN PYTHON
Purpose of constructor in python is that “to initialization the object”. Initializing the
object is nothing planning our value without leaving the content of object as empty.
100 | P a g e
WHAT IS CONSTRUCTOR IN PYTHON…?
Constructor is one of the special methods which is automatically called by PVM
during object creation and whose object purpose to place our own values without leaving the
object content is empty.
Or
In object-oriented programming, A constructor is a special method used to create
and initialize an object of a class. This method is defined in the class.
Note:
o For every object, the constructor will be executed only once. For example, if we
create four objects, the constructor is called four times.
o In Python, every class has a constructor, but it’s not required to define it explicitly.
Defining constructors in class is optional.
o Python will provide a default constructor if no constructor is defined.
TYPES OF CONSTRUCTORS:
1) Default constructor:
• Constructor is said to be default constructor if and only if it never takes parameter
/ value / arguments.
• The purpose of default constructor is that “to initialize multiple objects of same
class with same values”.
• Syntax:
def __init__(self):
:
101 | P a g e
Block of statements
2) Parameter constructor:
• A constructor with defined parameters or arguments is called a parameterized
constructor.
• We can pass different values to each object at the time of creation using a
parameterized constructor.
• Syntax:
def __init__ (self, para1, para2, …):
:
Block of statements
INHERITANCE IN PYTHON:
The purpose of Inheritance is that “To Build Re-Usable Applications”.
WHAT IS INHERITANCE…?
• The Process of obtaining the Data Members, Methods and constructors (Features)
from One Class into another Class is called Inheritance.
• The Class which is giving the Data Members, Methods and Constructors is called
Base / Super / Parent Class.
• The Class which is taking Data Members, Methods and Constructors is called
Derived / Sub / Child Class.
• Inheritance Principle always follows Logical Memory Management. This memory
management says that “Neither we write Physical Source Code nor takes Physical
memory Space”.
102 | P a g e
ADVANTAGES OF INHERITANCE:
• Application Development time is Less.
• Application Memory Space is Less.
• Application Execution time is Less.
• Application Performance is Enhanced (Improved).
• Redundancy of the code is Minimized.
103 | P a g e
TYPES OF INHERITANCE:
• Type of Inheritance is a model / Pattern / Diagram, which makes us to understand
how features are inherited from Base Class into Derived Class.
• In Python Programming, we have 5 types of Inheritances. They are,
1. Single Inheritance
2. Multi-Level Inheritance.
3. Hierarchical Inheritance.
4. Multiple Inheritance.
5. Hybrid Inheritance.
Now let’s see each in detail with an example.
1) SINGLE INHERITANCE:
• This inheritance contains single base class and single derive class.
Or
• In single inheritance, a child class inherits from a single-parent class.
• Here is one child class and one parent class.
105 | P a g e
2. MULTIPLE INHERITANCE:
• This inheritance contains multiple base classes and single derived class.
Or
• In multiple inheritance, one child class can inherit from multiple parent classes.
• So here is one child class and multiple parent classes.
3. HYBRID INHERITANCE:
• In hybrid inheritance, the combination of any available inheritance types.
Or
• When inheritance is consists of multiple types or a combination of different
inheritance is called hybrid inheritance.
106 | P a g e
MODULES IN PYTHON
107 | P a g e
1. THE RANDOM MODULE:
• Random is one predefined module in python.
• Purpose of this module is that “to generate” random values.
• Random module contains the following functions:
a) randomrange ():
• Returns a random number between the given range.
• This syntax gives random integer values in 0 to value-1.
• Syntax:
randrange(value)
Example:
import random
print("Random integer: ",[Link](5))
Output: 2
b) randomint ():
• Returns a random number between the given range.
• This syntax gives a random integer value in between begin and end (both of
them inclusive).
• Syntax:
[Link](begin, end)
Example, 1: example to generate random number.
import random
# random integer from 0 to 9
num1 = [Link](0, 9)
print(num1)
Output: 4
Example, 2: example to generate random number.
import random
# Random integer from 10 to 100
num2 = [Link](10, 100)
print(num2)
Output: 20
108 | P a g e
c) random ():
• This function generates random floating-point value in between 0.0 to 1.0 (both
of them are inclusive).
• Syntax:
[Link]()
Example:
import random
print([Link]())
Output: 0.5228549293497703
d) uniform ():
• This function generates random floating-points values in between begin and end
(both of them are inclusive).
• Syntax:
[Link](begin, end)
Example:
import random
print("Random Float uniform(5, 10) : ", [Link](5, 10))
Output: 5.52615217015
e) choice():
• This function is used selecting an arbitrary element from the given sequence or
iterable object.
• Choose a random item from a sequence. Here seq. can be a list, tuple, string, or
any iterable like range. It returns a single item from the sequence.
• If you pass an empty list or sequence to choice() It will raise IndexError
(Cannot choose from an empty sequence).
• Syntax:
[Link](sequence / iterable object)
Example, 1:
import random
num_list = [111, 222, 333, 444, 555, 666]
print(“Random Item from List”, [Link](num_list))
109 | P a g e
Output: Random Item from List: 333
Example, 2:
import random
food = ('PAV-BHAJI', 'MANCHURIAN', 'MISAL-PAV', 'IDALI-SAMBAR',
'VADA-RASAA', 'POHE')
print("Random Item from List: ", [Link](food))
Output: Random Item from List: MISAL-PAV
f) shuffle():
• This function is used for reorganizing the elements of iterable object (list,
bytearray) but not iterable immutable object.
• Takes a sequence and returns the sequence in a random order. shuffle a list, it
means a change in the order of list items.
• You can use [Link]() to mix up/randomize the items in a mutable and
indexable sequence. For example, shuffle a list of cards.
• Syntax:
[Link](iterable mutable object)
Example:
import random
number_list = [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
print("Original list: ", number_list)
[Link](number_list)
print("List after first shuffle: ", number_list)
[Link](number_list)
print("List after second shuffle: ", number_list)
Output: Original list: [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
List after first shuffle: [35, 42, 28, 7, 63, 21, 56, 70, 49, 14]
List after second shuffle: [56, 49, 28, 70, 35, 7, 21, 42, 14, 63]
g) sample():
• This function is used selecting number of random of samples based on the value
of ‘k’.
• sample() function for random sampling, randomly picking more than one
element from the list without repeating elements.
110 | P a g e
• It returns a list of unique items chosen randomly from the list, sequence, or set.
We call it random sampling without replacement.
• In simple terms, for example, we have a list of 100 names, and we want to
choose ten names randomly from it without repeating names, then we must use
[Link]().
• Syntax:
[Link](iterable object, k=no. of samples)
Example:
import random
a_List = [10,20,30,40,50,60,70,80,90,100]
sampled_list = [Link](a_List, 4)
print("choosing 4 random items from a list: ", sampled_list)
Output: choosing 4 random items from a list: [80, 20, 40, 10]
111 | P a g e
import module_name
module_name.function_name
Example: import operation
[Link]()
• Syntax, 2:
import module_name as alias name
Example: import pandas as pd
[Link] (-------//--------)
• Syntax, 3:
Module_name1, module_name2……module_name_n
2. By using from – import statement:
• from and import keyword
• from – import statement is also
• used importing the information about modules (variable, function, classes) of one
program into another program.
• Syntax:
from module_name import variable_name/function_name/class_name
Note:
• The module concept avoided the code reusability across the program provided the
program (modules) present in same folder but not able to provide code reusability
across the folder/driver/environment/network/module.
112 | P a g e
FILE HANDLING IN PYTHON
DEFINITION OF FILE:
• A file is collection record.
• A record is a collecting of values.
• All files are residing in secondary memory.
TYPE OF FILES:
• Text file: Ex. .txt, .py, .xml, .java
• Binary file: Ex. Audio, Video, Image file.
113 | P a g e
OPERATION ON FILE:
On file we perform 2 types of operation:
1. Write: - This operation is used for transferring object data of main memory into file
of secondary memory.
Steps:
a. Choose the file name.
b. Open file name in write mode.
c. Perform cycle of write operation.
2. Read: - This operation reads / transfer to data from file of secondary memory into the
object of main memory.
Steps:
a. Choose the file name.
b. Open the file name in read mode.
c. Perform cycle of read operation.
114 | P a g e
4. r+ With this mode first, we have to READ the data from file and later
we perform WRITE operation.
5. w+ With this mode first, we have to WRITE the data from file and later
we perform READ operation.
6. a+ This mode is used for creating the file and append that file in write
mode. If file is new then it starts writing from beginning AND if the
file existing the data is appended from the end. (If the file is new file,
then it creating as new file in write mode and opened in write mode
and start.)
7. x This mode is used for creating the file opening the file in
EXCLUSIVELY in write mode only. While we applying this mode
if the file already exists and we are opening the same file then we get
FileExistError.
115 | P a g e
READING THE DATA FROM FILE:
1. read():
• This function read entire data from file in the form of string.
• Syntax:
varname = [Link]()
Example:
file = input("Please enter your file name to read content: ")
with open(file, 'r') as cool:
mydata = [Link]()
print(mydata)
Output:
Please enter your file name to read content: [Link]
9 Factors of Python Popularity:
1. Python is easy to learn.
2. Python has an active, supportive community.
3. Python is flexible.
4. Python offers versatile web-development solutions.
5. Python is well suited to data science and analytics.
6. Python is efficient, fast, and reliable.
7. Python is widely used with IoT Technology.
8. Python empowers custom automation.
9. Python is the academic language.
116 | P a g e
2. readline():
• This function reads an entire line from the file in the form of string.
• Syntax:
Varname = [Link]()
Example:
myfile = open("[Link]", "r")
myline = [Link]()
print(myline)
[Link]()
Output: Testing - FirstLine
3. readlines():
• This function reads all the lines of specified file in the form of list.
• Syntax:
Listobj = [Link]()
Example:
file_obj = open("[Link]", "r", encoding="utf-8")
print(file_obj.readlines())
file_obj.close()
Output: This is a new file.
We have now learnt all read functions.
We are trying a new method
to loop over files.
117 | P a g e
4. read (no. of char):
• This function is used for reading specified number of characters from file.
• Syntax:
Varname = [Link](no. of character’s)
118 | P a g e
2) writelines():
• This function is used for writing any iterable object into the file in the form of
string.
• Syntax:
file_pointer.writeline(str(iterable object))
Example:
lines = ['Readme', 'How to write text files in Python']
with open('[Link]', 'w') as f:
[Link](lines)
Output: Readme
How to write text files in Python
119 | P a g e
• These errors are solved by programmer development time.
3) Runtime error:
• These errors occur at execution time.
• This error occurs due to invalid input enter by end user.
• This error solved by programmers during development with their forecasting
knowledge.
WHAT IS AN EXCEPTION...?
• Runtime error of a program is called exception.
TYPES OF EXCEPTION:
1) PREDEFINED ERROR:
120 | P a g e
5 ArithmeticError All mathematical computation errors belong to this base
class.
6 OverflowError This exception is raised when a computation surpasses
the numeric data type's maximum limit.
7 FloatingPointError If a floating-point operation fails, this exception is
raised.
8 ZeroDivisionError For all numeric data types, its value is raised whenever
a number is attempted to be divided by zero.
9 AssertionError If the Assert statement fails, this exception is raised.
10 AttributeError This exception is raised if a variable reference or
assigning a value fails.
11 EOFError When the endpoint of the file is approached, and the
interpreter didn't get any input value by raw_input() or
input() functions, this exception is raised.
12 ImportError This exception is raised if using the import keyword to
import a module fails.
13 KeyboardInterrupt If the user interrupts the execution of a program,
generally by hitting Ctrl+C, this exception is raised.
14 LookupError LookupErrorBase is the base class for all search errors.
15 IndexError This exception is raised when the index attempted to be
accessed is not found.
16 KeyError When the given key is not found in the dictionary to be
found in, this exception is raised.
17 NameError This exception is raised when a variable isn't located in
either local or global namespace.
18 UnboundLocalError This exception is raised when we try to access a local
variable inside a function, and the variable has not been
assigned any value.
19 EnvironmentError All exceptions that arise beyond the Python
environment have this base class.
20 IOError If an input or output action fails, like when using the
print command or the open() function to access a file
that does not exist, this exception is raised.
121 | P a g e
22 SyntaxError This exception is raised whenever a syntax error occurs
in our program.
23 IndentationError This exception was raised when we made an improper
indentation.
24 SystemExit This exception is raised when the [Link]() method is
used to terminate the Python interpreter. The parser
exits if the situation is not addressed within the code.
25 TypeError This exception is raised whenever a data type-
incompatible action or function is tried to be executed.
26 ValueError This exception is raised if the parameters for a built-in
method for a particular data type are of the correct type
but have been given the wrong values.
27 RuntimeError This exception is raised when an error that occurred
during the program's execution cannot be classified.
28 NotImplementedError If an abstract function that the user must define in an
inherited class is not defined, this exception is raised.
122 | P a g e
1) Try:
• Try block is called “exception monitoring”.
• It’s the block in which we write block of statement generating exception.
• Every try block must be immediately followed by except block.
• Syntax:
try:
block of statements
generating exception
except exception-class-name:
block of statements
generating user friendly error
messages
2) Except:
• It’s the block in which we write block of statements generates user friendly error
messages. Hence except is called “exception processing block”.
Note:
• Handling the exception = try block + except block
• Exception block will execute when the exception occurs in try block.
• The place of writing except block is that after try block and before else block.
3) Else:
• It’s the block, in which we write block of statements recommended for display
results.
• Else block will execute when there is no exception occur in try block.
• Writing else block is optional.
• The place of writing else block is after exceptional block and before finally block.
123 | P a g e
4) Finally:
• It’s the closing statement.
• Finally, will execute compulsorily irrespective of exception occurs or not.
• Writing finally will optional.
• The place of writing of finally block after else block (if else block is present).
5) Raise keyword:
• Raise keyword is used for hitting/raising/generating the exception when certain
condition is satisfied.
• PVM uses raise keyword for hitting predefined exception automatically.
• Syntax, 1:
if (test condition):
raise exception-class_name
• Syntax, 2:
def function_name(list of formal parameter):
if (test condition):
raise exception-class_name
124 | P a g e
METHOD OVERRIDING IN PYTHON
125 | P a g e
• Method Overriding avoids duplication of code
• Method Overriding also enhances the code adding some additional properties.
126 | P a g e
# It's own method - color
[Link]()
print("Old value of data1 = ", sq.data1)
# Override property of the Parent class
sq.data1 = "New value"
print("The value of data1 in Shape class overridden by the Square class = ", sq.data1)
Output:
I have 4 sides. I am from Square class
I am a 2D object. I am from shape class
I have teal color. I am from Square class.
Old value of data1 = abc
The value of data1 in Shape class overridden by the Square class = New value
POLYMORPHISM IN PYTHON:
• With super () we are able to call only immediate base class method but unable to call
specified method of base class to do this we must use class name approach.
• Syntax: super().method name(list of value if any)
• Syntax: super().__init__(list of value if any)
128 | P a g e
• Helps in implementing modularity (isolating changes) and code reusability.
Example:
# Parent Class
class Vehicle:
def __init__(self, company, model, year, color):
[Link] = company
[Link] = model
[Link] = year
[Link] = color
# Child Class
class Car(Vehicle):
def __init__(self, company, model, year, color, car_type):
# Using super to access __init__ method of Parent Class
super().__init__(company, model, year, color)
self.car_type = car_type
# Creating an object of Car
my_car = Car("Tesla", "S", 2021, "Silver", "Sedan")
print(f"I have a {my_car.company} model {my_car.model}.")
Output: I have a Tesla model S.
129 | P a g e
OS MODULE IN PYTHON
A) CREATE FOLDER:
• In Python the ‘[Link]()’ function is used to create a directory (Folder).
• Inside the ‘[Link]’ function we have to just pass a path as an argument where
you want to create a directory. Here mkdir stands for Make Directory.
• Predefined function: Mkdir()
• Syntax: [Link](“folder name”)
This function creates one folder at a time and unable to create folder hierarchy.
Example:
import os
[Link](r"C:\Users\Dell\Desktop\Scaler Content")
[Link](r"C:\Users\Dell\Desktop\InterviewBit")
130 | P a g e
C) DELET FOLDER:
• Rmdir()
• Syntax: [Link](“folder name”)
• This function can remove one folder at a time provided that folder should not
contain any files otherwise we get OSERROR.
D) Listing the file of the folder:
• To list the filst of a folder we use listdir() and return all the files of a specified
folder but not listing sub and sub-sub folder files.
• Syntax : listobj=[Link](“folder name”)
E) Listing the files of root folder sub folder, sub-sub folder:
• To list the files of root folder, sub-sub folder etc. we use walk().
• Syntax: listobj=[Link]()
PACKAGES IN PYTHON
131 | P a g e
as a package.
• It generally contains the initialization code but may also be left empty.
• A possible hierarchical representation of the shifting items package in the first
example can be given below.
➢ CREATING A PACKAGE.
1. Create folder.
2. Place an empty python file on the name of __init__.py in folder.
3. Defined a module in package.
Or
1. Create a directory for the package.
2. Add python module files to the package directory.
3. Create a python file named __init__.py in the package directory.
Code in Python packages can be accessed using the same type of import statements that are
used for modules.
Example Package:
This package directory will be named: util
The util directory will hold two modules – each with two functions plus an empty __init_.py
file:
[Link]
halved()
doubled()
[Link]
132 | P a g e
squared()
cubed()
__init__.py
133 | P a g e