Comprehensive Python Programming Guide
Comprehensive Python Programming Guide
Python is a widely used programming language that offers several unique features and
advantages compared to languages like Java and C++. Our Python tutorial thoroughly explains
Python basics and advanced concepts, starting with installation, conditional
statements, loops, built-in data structures, Object-Oriented Programming, Generators, Exception
Handling, Python RegEx, and many other concepts. This tutorial is designed for beginners and
working professionals.
In the late 1980s, Guido van Rossum dreamed of developing Python. The first version of Python
0.9.0 was released in 1991. Since its release, Python started gaining popularity. According to
reports, Python is now the most popular programming language among developers because of its
high demands in the tech realm.
Python
Importance of Python:
o Easy to use and Read - Python's syntax is clear and easy to read, making it an ideal
language for both beginners and experienced programmers. This simplicity can lead to
faster development and reduce the chances of errors.
o Dynamically Typed - The data types of variables are determined during run-time. We do
not need to specify the data type of a variable during writing codes.
o High-level - High-level language means human readable code.
o Compiled and Interpreted - Python code first gets compiled into bytecode, and then
interpreted line by line. When we download the Python in our system form org we download
the default implement of Python known as CPython. CPython is considered to be Complied
and Interpreted both.
o Garbage Collected - Memory allocation and de-allocation are automatically managed.
Programmers do not specifically need to manage the memory.
1
o Purely Object-Oriented - It refers to everything as an object, including numbers and
strings.
o Cross-platform Compatibility - Python can be easily installed on Windows, macOS, and
various Linux distributions, allowing developers to create software that runs across different
operating systems.
o Rich Standard Library - Python comes with several standard libraries that provide ready-
to-use modules and functions for various tasks, ranging from web development and data
manipulation to machine learning and networking.
o Open Source - Python is an open-source, cost-free programming language. It is utilized in
several sectors and disciplines as a result.
Python has many web-based assets, open-source projects, and a vibrant community. Learning the
language, working together on projects, and contributing to the Python ecosystem are all made
very easy for developers. Because of its straightforward language framework, Python is easier to
understand and write code in. This makes it a fantastic programming language for novices.
Additionally, it assists seasoned programmers in writing clear and error-free code.
Python has many third-party libraries that can be used to make its functionality easier. These
libraries cover many domains, for example, web development, scientific computing, data analysis,
and more.
For example -
1. def func():
2. statement 1
3. statement 2
4. …………………
5. …………………
6. statement N
2
In the above example, the statements that are the same level to the right belong to the function.
Generally, we can use four whitespaces to define indentation. Instead of Semicolon as used in
other languages, Python ends its statements with a NewLine character.
Python is a case-sensitive language, which means that uppercase and lowercase letters are
treated differently. For example, 'name' and 'Name' are two different variables in Python. In
Python, comments can be added using the '#' symbol. Any text written after the '#' symbol is
considered a comment and is ignored by the interpreter. This trick is useful for adding notes to the
code or temporarily disabling a code block. It also helps in understanding the code better by some
other developers.
'If', 'otherwise', 'for', 'while', 'try', 'except', and 'finally' are a few reserved keywords in Python that
cannot be used as variable names. These terms are used in the language for particular reasons
and have fixed meanings. If you use these keywords, your code may include errors, or the
interpreter may reject them as potential new Variables.
History of Python
Python was created by Guido van Rossum. In the late 1980s, Guido van Rossum, a Dutch
programmer, began working on Python while at the Centrum Wiskunde & Informatica (CWI) in the
Netherlands. He wanted to create a successor to the ABC programming language that would be
easy to read and efficient.
In February 1991, the first public version of Python, version 0.9.0, was released. This marked
the official birth of Python as an open-source project. The language was named after the British
comedy series "Monty Python's Flying Circus".
Python development has gone through several stages. In January 1994, Python 1.0 was
released as a usable and stable programming language. This version included many of the
features that are still present in Python today.
From the 1990s to the 2000s, Python gained popularity for its simplicity, readability, and
versatility. In October 2000, Python 2.0 was released. Python 2.0 introduced list
comprehensions, garbage collection, and support for Unicode.
In December 2008, Python 3.0 was released. Python 3.0 introduced several backward-
incompatible changes to improve code readability and maintainability.
3
Throughout 2010s, Python's popularity increased, particularly in fields like data science, machine
learning, and web development. Its rich ecosystem of libraries and frameworks made it a favourite
among developers.
The Python Software Foundation (PSF) was established in 2001 to promote, protect, and
advance the Python programming language and its community.
AD
Features of Python
Python provides many useful features to the programmer. These features make it the most popular
and widely used language. We have listed below few-essential features of Python.
o Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike
traditional languages like C, C++, Java, etc., making it easy for beginners to learn.
o Expressive Language: It allows programmers to express complex concepts in just a few
lines of code or reduces Developer's Time.
o Interpreted Language: Python does not require compilation, allowing rapid development
and testing. It uses Interpreter instead of Compiler.
o Object-Oriented Language: It supports object-oriented programming, making writing
reusable and modular code easy.
o Open-Source Language: Python is open-source and free to use, distribute and modify.
o Extensible: Python can be extended with modules written in C, C++, or other languages.
o Learn Standard Library: Python's standard library contains many modules and functions
that can be used for various tasks, such as string manipulation, web programming, and
more.
o GUI Programming Support: Python provides several GUI frameworks, such
as Tkinter and PyQt, allowing developers to create desktop applications easily.
o Integrated: Python can easily integrate with other languages and technologies, such as
C/C++, Java, and . NET.
o Embeddable: Python code can be embedded into other applications as a scripting
language.
4
o Dynamic Memory Allocation: Python automatically manages memory allocation, making it
easier for developers to write complex programs without worrying about memory
management.
o Wide Range of Libraries and Frameworks: Python has a vast collection of libraries and
frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a wide
range of problems.
o Versatility: Python is a universal language in various domains such as web
development, machine learning, data analysis, scientific computing, and more.
o Large Community: Python has a vast and active community of developers contributing to
its development and offering support. This makes it easy for beginners to get help and learn
from experienced developers.
o Career Opportunities: Python is a highly popular language in the job market. Learning
Python can open up several career opportunities in data science, artificial intelligence, web
development, and more.
o High Demand: With the growing demand for automation and digital transformation, the
need for Python developers is rising. Many industries seek skilled Python developers to
help build their digital infrastructure.
o Increased Productivity: Python has a simple syntax and powerful libraries that can help
developers write code faster and more efficiently. This can increase productivity and save
time for developers and organizations.
o Big Data and Machine Learning: Python has become the go-to language for big data and
machine learning. Python has become popular among data scientists and machine learning
engineers with libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and more.
AD
Applications of Python
o Data Science: Data Science is a vast field, and Python is an important language for this
field because of its simplicity, ease of use, and availability of powerful data analysis and
visualization libraries like NumPy, Pandas, and Matplotlib.
5
o Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI -
Graphical User Interface-based Desktop Applications. There are better languages for this
field, but it can be used with other languages for making Applications.
o Console-based Applications: Python is also commonly used to create command-line or
console-based applications because of its ease of use and support for advanced features
such as input/output redirection and piping.
o Mobile Applications: While Python is not commonly used for creating mobile applications,
it can still be combined with frameworks like Kivy or BeeWare to create cross-platform
mobile applications.
o Software Development: Python is considered one of the best software-making languages.
Python is easily compatible with both from Small Scale to Large Scale software.
o Artificial Intelligence: AI is an emerging Technology, and Python is a perfect language for
artificial intelligence and machine learning because of the availability of powerful libraries
such as TensorFlow, Keras, and PyTorch.
o Web Applications: Python is commonly used in web development on the backend with
frameworks like Django and Flask and on the front end with tools
like JavaScript HTML and CSS.
o Enterprise Applications: Python can be used to develop large-scale enterprise
applications with features such as distributed computing, networking, and parallel
processing.
o 3D CAD Applications: Python can be used for 3D computer-aided design (CAD)
applications through libraries such as Blender.
o Machine Learning: Python is widely used for machine learning due to its simplicity, ease of
use, and availability of powerful machine learning libraries.
o Computer Vision or Image Processing Applications: Python can be used for computer
vision and image processing applications through powerful libraries such as OpenCV and
Scikit-image.
o Speech Recognition: Python can be used for speech recognition applications through
libraries such as SpeechRecognition and PyAudio.
o Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced
numerical computing capabilities for tasks like data analysis, machine learning, and more.
o Education: Python's easy-to-learn syntax and availability of many resources make it an
ideal language for teaching programming to beginners.
6
o Testing: Python is used for writing automated tests, providing frameworks like unit tests
and pytest that help write test cases and generate reports.
o Gaming: Python has libraries like Pygame, which provide a platform for developing games
using Python.
o IoT: Python is used in IoT for developing scripts and applications for devices like Raspberry
Pi, Arduino, and others.
o Networking: Python is used in networking for developing scripts and applications for
network automation, monitoring, and management.
o DevOps: Python is widely used in DevOps for automation and scripting of infrastructure
management, configuration management, and deployment processes.
o Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial
modeling and analysis.
o Audio and Music: Python has libraries like Pyaudio, which is used for audio processing,
synthesis, and analysis, and Music21, which is used for music analysis and generation.
o Writing scripts: Python is used for writing utility scripts to automate tasks like file
operations, web scraping, and data processing.
AD
Python has wide range of libraries and frameworks widely used in various fields such as machine
learning, artificial intelligence, web applications, etc. We define some popular frameworks and
libraries of Python as follows.
7
o Pytest: a testing framework for Python Django
o REST framework: a toolkit for building RESTful APIs
o FastAPI: a modern, fast web framework for building APIs
o Streamlit: a library for building interactive web apps for machine learning and data science
o NLTK: a library for natural language processing
Comments
Python Comments
We'll study how to write comments in our program in this article. We'll also learn about single-line
comments, multi-line comments, documentation strings, and other Python comments.
We may wish to describe the code we develop. We might wish to take notes of why a section of
script functions, for instance. We leverage the remarks to accomplish this. Formulas, procedures,
and sophisticated business logic are typically explained with comments. The Python interpreter
overlooks the remarks and solely interprets the script when running a program. Single-line
comments, multi-line comments, and documentation strings are the 3 types of comments in
Python.
Our code is more comprehensible when we use comments in it. It assists us in recalling why
specific sections of code were created by making the program more understandable.
Aside from that, we can leverage comments to overlook specific code while evaluating other code
sections. This simple technique stops some lines from running or creates a fast pseudo-code for
the program.
8
Python Keywords
Every scripting language has designated words or keywords, with particular definitions and usage
guidelines. Python is no exception. The fundamental constituent elements of any Python program
are Python keywords.
Every language contains words and a set of rules that would make a sentence meaningful.
Similarly, in Python programming language, there are a set of predefined words, called Keywords
which along with Identifiers will form meaningful sentences when used together. Python keywords
cannot be used as the names of variables, functions, and classes.
Python keywords are unique words reserved with defined meanings and functions that we can only
apply for those functions. You'll never need to import any keyword into your program because
they're permanently present.
Python's built-in methods and classes are not the same as the keywords. Built-in methods and
classes are constantly present; however, they are not as limited in their application as keywords.
Assigning a particular meaning to Python keywords means you can't use them for other purposes
in our code. You'll get a message of SyntaxError if you attempt to do the same. If you attempt to
assign anything to a built-in method or type, you will not receive a SyntaxError message; however,
it is still not a smart idea.
Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have
shown a complete list of Python keywords for the reader's reference.
9
assert del global not with
Keywords in Python
Python Keywords are some predefined and reserved words in Python that have special meanings.
Keywords are used to define the syntax of the coding. The keyword cannot be used as an
identifier, function, or variable name. All the keywords in Python are written in lowercase except
True and False. There are 35 keywords in Python 3.11.
In Python, there is an inbuilt keyword module that provides an iskeyword() function that can be
used to check whether a given string is a valid keyword or not. Furthermore, we can check the
name of the keywords in Python by using the kwlist attribute of the keyword module.
Identifiers
Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The identifier is a
combination of character digits and an underscore. They are case-sensitive i.e., ‘num’ and ‘Num’
and ‘NUM’ are three different identifiers in python. It is a good programming practice to give
meaningful names to identifiers to make the code understandable.
We can also use the Python string isidentifier() method to check whether a string is a valid
identifier or not.
10
Examples of Python Identifiers
Valid identifiers:
• var1
• _var1
• _1_var
• var_1
Invalid Identifiers
• !var1
• 1var
• 1_var
• var#1
• var 1
Python Variables
A variable is the name given to a memory location. A value-holding Python variable is also known
as an identifier.
Since Python is an infer language that is smart enough to determine the type of a variable, we do
not need to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can be a group of both letters
and digits. The name of the variable should be written in lowercase. Both Rahul and rahul are
distinct variables.
Python Variable is containers that store values. Python is not “statically typed”. We do not need to
declare variables before using them or declare their type. A variable is created the moment we first
assign a value to it. A Python variable is a name given to a memory location. It is the basic unit of
storage in a program. In this article, we will see how to define a variable in Python.
11
“Geeksforgeeks” in a variable var, and when we call its name the stored information will get
printed.
• A Python variable name must start with a letter or the underscore character.
• A Python variable name cannot start with a number.
• A Python variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ ).
• Variable in Python names are case-sensitive (name, Name, and NAME are three different
variables).
• The reserved words(keywords) in Python cannot be used to name the variable in Python.
Identifier Naming
Identifiers are things like variables. An Identifier is utilized to recognize the literals utilized in the
program. The standards to name an identifier are given underneath.
12
Declaring Variable and Assigning Values
Object References
When we declare a variable, it is necessary to comprehend how the Python interpreter works.
Compared to a lot of other programming languages, the procedure for dealing with variables is a
little different.
Python is the exceptionally object-arranged programming language; Because of this, every data
item is a part of a particular class. Think about the accompanying model.
We use Python assignment statements to assign objects to names. The target of an assignment
statement is written on the left side of the equal sign (=), and the object on the right can be an
arbitrary expression that computes an object.
1. Basic form:
student = 'Geeks'
print(student)
13
2. Tuple assignment:
x, y = 50, 100
print('x = ', x)
print('y = ', y)
3. List assignment:
[x, y] = [2, 4]
print('x = ', x)
print('y = ', y)
Python Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data. Since everything is an
object in Python programming, Python data types are classes and variables are instances
(objects) of these classes. The following are the standard or built-in data types in Python:
1. Numeric
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
6. Binary Types( memoryview, bytearray, bytes)
14
What is Python Data Types?
To define the values of various data types of Python and check their data types we use the type()
function. Consider the following examples.
This code assigns variable ‘x’ different values of various Python data types. It covers string,
integer, float, complex, list, tuple, range, dictionary, set, frozenset, boolean, bytes, bytearray,
memoryview, and the special value ‘None’ successively. Each assignment replaces the previous
value, making ‘x’ take on the data type and value of the most recent assignment.
The numeric data type in Python represents the data that has a numeric value. A numeric value
can be an integer, a floating number, or even a complex number. These values are defined as
Python int, Python float, and Python complex classes in Python.
15
1. Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
2. Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by
a positive or negative integer may be appended to specify scientific notation.
3. Complex Numbers – A complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of Python data type.
Example: This code demonstrates how to determine the data type of variables in Python using the
type() function. It prints the data types of three variables: a (integer), b (float), and c (complex). The
output shows the respective data type Python for each variable.
The sequence Data Type in Python is the ordered collection of similar or different Python data
types. Sequences allow storing of multiple values in an organized and efficient fashion. There are
several sequence data types of Python:
1. Python String
2. Python List
3. Python Tuple
Data types specify the different sizes and values that can be stored in the variable. For example,
Python stores numbers, strings, and a list of values using different data types.
There are mainly four types of basic/primitive data types available in Python
16
• Numeric: int, float, and complex
• Set
• Dictionary (dict)
To check the data type of variable use the built-in function type() and isinstance().
In this article, we will learn the following Python data types in detail.
17
The string type in Python is represented using a str class.
To work with text or character data in Python, we use Strings. Once a string is created, we can do
many operations on it, such as searching inside it, creating a substring from it, and splitting it.
Python uses the int data type to represent whole integer values. For example, we can use the int
data type to store the roll number of a student. The Integer type in Python is represented using
a int class. You can store positive and negative integer numbers of any length such as 235, -758,
235689741. We can create an integer variable using the two ways
You can also store integer values other than base 10 such as
• Binary (base 2)
• Octal (base 8)
To represent floating-point values or decimal values, we can use the float data type. For
example, if we want to store the salary, we can use the float type.
Floating-point values can be represented using the exponential form, also called scientific
notation. The benefit of using the exponential form to represent floating-point values is we can
represent large values using less memory.
18
Complex data type
The complex type is generally used in scientific applications and electrical engineering
applications. If we want to declare a complex value, then we can use the a+bj form. See the
following example.
The real part of the complex number is represented using an integer value. The integer value can
be in the form of either decimal, float, binary, or hexadecimal. But the imaginary part should be
represented using the decimal form only. If we are trying to represent an imaginary part as binary,
hex, or octal, we will get an error.
The Python List is an ordered collection (also known as a sequence ) of elements. List
elements can be accessed, iterated, and removed according to the order they inserted at the
creation time.
We use the list data type to represent groups of the element as a single entity. For example: If we
want to store all student’s names, we can use list type.
1. The list can contain data of all data types such as int, float, string
2. Duplicates elements are allowed in the list
3. The list is mutable which means we can modify the value of list elements
Tuples are ordered collections of elements that are unchangeable. The tuple is the same as
the list, except the tuple is immutable means we can’t modify the tuple once created.
19
In other words, we can say a tuple is a read-only version of the list.
For example: If you want to store the roll numbers of students that you don’t change, you can use
the tuple data type.
Note: Tuple maintains the insertion order and also, allows us to store duplicate elements.
In Python, dictionaries are unordered collections of unique values stored in (Key-Value) pairs.
Use a dictionary data type to store data as a key-value pair.
The dictionary type is represented using a dict class. For example, If you want to store the name
and roll number of all students, then you can use the dict type.
In a dictionary, duplicate keys are not allowed, but the value can be duplicated. If we try to insert a
value with a duplicate key, the old value will be replaced with the new value.
1. A heterogeneous (i.e., str, list, tuple) elements are allowed for both key and value in a
dictionary. But An object can be a key in a dictionary if it is hashable.
2. The dictionary is mutable which means we can modify its items
3. Dictionary is unordered so we can’t perform indexing and slicing
20
Set data type
In Python, a set is an unordered collection of data items that are unique. In other words,
Python Set is a collection of elements (Or objects) that contains no duplicate elements.
In Python, the Set data type used to represent a group of unique elements as a single entity. For
example, If we want to store student ID numbers, we can use the set data type.
Frozenset
The frozenset data type is used to create the immutable Set. Once we create a frozenset,
then we can’t perform any changes on it.
In Python, to represent boolean values (True and False) we use the bool data type. Boolean
values are used to evaluate the value of the expression. For example, when we compare two
values, the expression is evaluated, and Python returns the boolean True or False.
21
bytearray
The bytearray data type same as the bytes type except bytearray mutable (we can modify its
elements). The bytearray() constructor returns a bytearray object.
In Python, The built-in function range() used to generate a sequence of numbers from a start
number up to the stop number. For example, If we want to represent the roll number from 1 to 20,
we can use the range() type. By default, it returns an iterator object that we can iterate using a for
loop.
memoryview
The memoryview is used to create a view of the internal data of an object without copying it. So
with the help of memoryview we can see the same data in a different view.
To do this, we need a buffer protocol. The buffer protocol provides a way to access the internal
data of an object. This internal data is a memory array or a buffer.
n Python bytes and bytearray are built-in objects that support the buffer protocol. So we can
create memoryview on top of those objects.
In the above example, we create memoryview of b_array and print the object in memory view
format instead of the original object. If we want an object in its original form, we need to collect the
object in a container(like a list or tuple). We can also iterate over each element of the given bytes
array.
We can also perform indexing and slicing on memoryview same like list and tuple object. So it will
return ordinal value for characters at the given index.
Python Operators
In Python programming, Operators in general are used to perform operations on values and
variables. These are standard symbols used for logical and arithmetic operations. In this article, we
will look into different types of Python operators.
22
• OPERATORS: These are the special symbols. Eg- + , * , /, etc.
• OPERAND: It is the value on which the operator is applied.
•
Types of Operators in Python
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Python Operators
Introduction:
In this article, we are discussing Python Operators. The operator is a symbol that performs a
specific operation between two operands, according to one definition. Operators serve as the
foundation upon which logic is constructed in a program in a particular programming language. In
every programming language, some operators perform several tasks. Same as other languages,
Python also has some operators, and these are given below -
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators
Arithmetic Operators
Arithmetic operators used between two operands for a particular operation. There are many
arithmetic operators. It includes the exponent (**) operator as well as the + (addition), -
(subtraction), * (multiplication), / (divide), % (reminder), and // (floor division) operators.
23
Consider the following table for a detailed explanation of arithmetic operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b =
20
- (Subtraction) It is used to subtract the second operand from the first operand. If the
first operand is less than the second operand, the value results negative.
For example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b
(Multiplication) = 4 => a * b = 80
% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0
// (Floor It provides the quotient's floor value, which is obtained by dividing the
division) two operands.
Program Code:
Now we give code examples of arithmetic operators in Python. The code is given below -
24
9. print('Floor division of two numbers:',a//b)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the
output is given below -
Comparison operator
Comparison operators mainly use for comparison purposes. Comparison operators compare the
values of the two operands and return a true or false Boolean value in accordance. The example
of comparison operators are ==, !=, <=, >=, >, <. In the below table, we explain the works of the
operators.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second
operand.
>= The condition is met if the first operand is greater than or equal to the second
operand.
> If the first operand is greater than the second operand, then the condition
becomes true.
< If the first operand is less than the second operand, then the condition becomes
25
true.
Program Code:
Now we give code examples of Comparison operators in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the
output is given below -
Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left operand. There
are some examples of assignment operators like =, +=, -=, *=, %=, **=, //=. In the below table, we
explain the works of the operators.
Operator Description
26
+= By multiplying the value of the right operand by the value of the left operand,
the left operand receives a changed value. For example, if a = 10, b = 20 => a+
= b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand. For example, if a = 20, b = 10
=> a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and
assigns the modified value back to then the left operand. For example, if a =
10, b = 20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and
assigns the reminder back to the left operand. For example, if a = 20, b = 10 =>
a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2
= 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3
= 1 to a.
Program Code:
Now we give code examples of Assignment operators in Python. The code is given below -
27
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the
output is given below -
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples of
Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift (<<),
and Right shift (>>). Consider the case below.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
10. Let, Binary of x = 0101
11. Binary of y = 1000
12. Bitwise OR = 1101
13. 8 4 2 1
14. 1 1 0 1 = 8 + 4 + 1 = 13
15.
16. Bitwise AND = 0000
28
17. 0000 = 0
18.
19. Bitwise XOR = 1101
20. 8 4 2 1
21. 1 1 0 1 = 8 + 4 + 1 = 13
22. Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6
23. ~x = -6
In the below table, we are explaining the works of the bitwise operators.
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same location
and) are 1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting
bit will be 1.
^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the
next bit will be 1, and vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of
the value of the left operand.
>> (right shift) The left operand is moved right by the number of bits present in the right
operand.
Program Code:
Now we give code examples of Bitwise operators in Python. The code is given below -
29
6. print('~a:', ~a)
7. print('a<<b:', a<<b)
8. print('a>>b:', a>>b)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the
output is given below -
a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0
Logical Operators
The assessment of expressions to make decisions typically uses logical operators. The examples
of logical operators are and, or, and not. In the case of logical AND, if the first one is 0, it does not
depend upon the second one. In the case of logical OR, if the first one is 1, it does not depend on
the second one. Python supports the following logical operators. In the below table, we explain the
works of the logical operators.
Operator Description
and The condition will also be true if the expression is true. If the two expressions a
and b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Program Code:
Now we give code examples of arithmetic operators in Python. The code is given below -
30
2. print(Is this statement true?:',a > 3 and a < 5)
3. print('Any one statement is true?:',a > 3 or a < 5)
4. print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5)))
Output:
Now we give code examples of Bitwise operators in Python. The code is given below -
Membership Operators
The membership of a value inside a Python data structure can be verified using Python
membership operators. The result is true if the value is in the data structure; otherwise, it returns
false.
Operator Description
not in If the first operand is not present in the second operand, the evaluation is true
(list, tuple, or dictionary).
Program Code:
Now we give code examples of Membership operators in Python. The code is given below -
1. x = ["Rose", "Lotus"]
2. print(' Is value Present?', "Rose" in x)
3. print(' Is value not Present?', "Riya" not in x)
Output:
31
Now we compile the above code in Python, and after successful compilation, we run it. Then the
output is given below -
Identity Operators
Operator Description
is If the references on both sides point to the same object, it is determined to be true.
is not If the references on both sides do not point at the same object, it is determined to be
true.
Program Code:
Now we give code examples of Identity operators in Python. The code is given below -
1. a = ["Rose", "Lotus"]
2. b = ["Rose", "Lotus"]
3. c = a
4. print(a is c)
5. print(a is not c)
6. print(a is b)
7. print(a is not b)
8. print(a == b)
9. print(a != b)
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the
output is given below -
True
False
False
True
32
True
False
Operator Precedence
The order in which the operators are examined is crucial to understand since it tells us which
operator needs to be considered first. Below is a list of the Python operators' precedence tables.
Operator Description
* / % // the division of the floor, the modules, the division, and the multiplication.
<= < > >= Comparison operators (less than, less than equal to, greater than, greater
then equal to).
33
Python Built in Functions
Function Description
34
otherwise False
35
exec() Executes the specified code (or object)
36
input() Allowing user input
37
next() Returns the next item in an iterable
38
setattr() Sets an attribute (property/method) of an object
39
Python string methods is a collection of in-built Python functions that operates on lists.
Note: Every string method in Python does not change the original string instead returns a new
string with the changed attributes.
Python string is a sequence of Unicode characters that is enclosed in quotation marks. In this
article, we will discuss the in-built string functions i.e. the functions provided by Python to
operate on strings.
The below Python functions are used to change the case of the strings. Let’s look at some
Python string methods with examples:
capitalize() Converts the first character of the string to a capital (uppercase) letter
40
Function Name Description
Specifies the amount of space to be substituted with the “\t” symbol in the
expandtabs()
string
isalnum() Checks whether all the characters in a given string is alphanumeric or not
isnumeric() Returns “True” if all characters in the string are numeric characters
Returns “True” if all characters in the string are printable or the string is
isprintable()
empty
isspace() Returns “True” if all characters in the string are whitespace characters
41
Function Name Description
rindex() Returns the highest index of the substring inside the string
rsplit() Split the string from the right by the specified separator
42
Function Name Description
strip() Returns the string with both leading and trailing characters
Returns a copy of the string with ‘0’ characters padded to the left side of
zfill()
the string
43
if condition:
# Statements to execute if
# condition is true
• Python
# if statement example
if 10 > 5:
print("Program ended")
Output
10 greater than 5
Program ended
• Python
44
x=3
if x == 4:
print("Yes")
else:
print("No")
Output
No
• Python
letter = "A"
if letter == "B":
print("letter is B")
else:
if letter == "C":
print("letter is C")
45
else:
if letter == "A":
print("letter is A")
else:
Output
letter is A
• Python
letter = "A"
if letter == "B":
print("letter is B")
print("letter is C")
46
elif letter == "A":
print("letter is A")
else:
Output
letter is A
• Python
a, b = 10, 20
print ("Both a and b are equal" if a == b else "a is greater than b"
Output
b is greater than a
47
Best Practices for Using Conditional Statements
1. Keep conditions simple and expressive for better readability.
2. Avoid deeply nested conditional blocks; refactor complex logic into smaller, more
manageable functions.
3. Comment on complex conditions to clarify their purpose.
4. Prefer the ternary operator for simple conditional assignments.
5. Advanced Techniques:
6. Using short-circuit evaluation for efficiency in complex conditions.
7. Leveraging + with conditions applied to iterables.
8. Employing conditional expressions within list comprehensions and generator expressions.
Python - Regular Expressions
A regular expression is a special sequence of characters that helps you match or find other strings
or sets of strings, using a specialized syntax held in a pattern. Regular expression are popularly
known as regex or regexp.
Usually, such patterns are used by string-searching algorithms for "find" or "find and replace"
operations on strings, or for input validation.
Large scale text processing in data science projects requires manipulation of textual data. The
regular expressions processing is supported by many programming languages including Python.
Python's standard library has re module for this purpose.
Since most of the functions defined in re module work with raw strings, let us first understand what
the raw strings are.
Raw Strings
Regular expressions use the backslash character ('\') to indicate special forms or to allow special
characters to be used without invoking their special meaning. Python on the other hand uses the
same character as escape character. Hence Python uses the raw string notation.
48
Regular Expressions in Python
1. Introduction
o Searching text
o Validating inputs
o Extracting substrings
2. The re Module
import re
49
Metacharacters
Most letters and characters will simply match themselves. However, some characters are special
metacharacters, and don't match themselves. Meta characters are characters having a special
meaning, similar to * in wild card.
.^$*+?{}[]\|()
The square bracket symbols[ and ] indicate a set of characters that you wish to match. Characters
can be listed individually, or as a range of characters separating them by a '-'.
[abc]
1
match any of the characters a, b, or c
[a-c]
2
which uses a range to express the same set of characters.
[a-z]
3
match only lowercase letters.
[0-9]
4
match only digits.
'^'
5
complements the character set in [].[^5] will match any character except'5'.
'\'is an escaping metacharacter. When followed by various characters it forms various special
sequences. If you need to match a [ or \, you can precede them with a backslash to remove their
special meaning: \[ or \\.
50
Predefined sets of characters represented by such special sequences beginning with '\' are listed
below –
\d
1
Matches any decimal digit; this is equivalent to the class [0-9].
\D
2
Matches any non-digit character; this is equivalent to the class [^0-9].
\S
4
Matches any non-whitespace character; this is equivalent to the class [^\t\n\r\f\v].
\w
5
Matches any alphanumeric character; this is equivalent to the class [a-zAZ0-9_].
\W
6
Matches any non-alphanumeric character. equivalent to the class [^a-zAZ0-9_].
.
7
Matches with any single character except newline '\n'.
?
8
match 0 or 1 occurrence of the pattern to its left
9 +
51
1 or more occurrences of the pattern to its left
*
10
0 or more occurrences of the pattern to its left
\b
11
boundary between word and non-word and /B is opposite of /b
[..]
12 Matches any single character in a square bracket and [^..] matches any single
character not in square bracket.
\
13
It is used for special meaning characters like \. to match a period or \+ for plus sign.
{n,m}
14
Matches at least n and at most m occurrences of preceding
a| b
15
Matches either a or b
Python's re module provides useful functions for finding a match, searching for a pattern, and
substitute a matched string with other string etc.
This function attempts to match RE pattern at the start of string with optional flags. Following is
the syntax for this function −
52
[Link]. Parameter & Description
pattern
1
This is the regular expression to be matched.
String
2 This is the string, which would be searched to match the pattern at the
beginning of string.
Flags
3 You can specify different flags using bitwise OR (|). These are modifiers, which
are listed in the table below.
The [Link]() function returns a match object on success, None on failure. A match object
instance contains information about the match: where it starts and ends, the substring it matched,
etc.
The match object's start() method returns the starting position of pattern in the string, and end()
returns the endpoint.
groups()This method returns all matching subgroups in a tuple (empty if there weren't
2
any)
53
Pattern
1
This is the regular expression to be matched.
String
2 This is the string, which would be searched to match the pattern anywhere in the
string.
Flags
3 You can specify different flags using bitwise OR (|). These are modifiers, which are
listed in the table below.
Matching Vs Searching
Python offers two different primitive operations based on regular expressions, match checks for a
match only at the beginning of the string, while search checks for a match anywhere in the string
(this is what Perl does by default).
Parameters
1 Pattern
54
This is the regular expression to be matched.
String
2 This is the string, which would be searched to match the pattern anywhere in the
string.
Flags
3 You can specify different flags using bitwise OR (|). These are modifiers, which
are listed in the table below.
Flags
re.I
1
Performs case-insensitive matching.
re.L
2 Interprets words according to the current locale. This interpretation affects the
alphabetic group (\w and \W), as well as word boundary behavior (\b and \B).
re.
3 M Makes $ match the end of a line (not just the end of the string) and makes ^
match the start of any line (not just the start of the string).
re.S
4
Makes a period (dot) match any character, including a newline.
5 re.U
55
Interprets letters according to the Unicode character set. This flag affects the
behavior of \w, \W, \b, \B.
re.X
Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You can
escape a control character by preceding it with a backslash.
Following table lists the regular expression syntax that is available in Python −
^
1
Matches beginning of line.
$
2
Matches end of line.
3 Matches any single character except newline. Using m option allows it to match
newline as well.
[...]
4
Matches any single character in brackets.
[^...]
5
Matches any single character not in brackets
56
re*
6
Matches 0 or more occurrences of preceding expression.
re+
7
Matches 1 or more occurrence of preceding expression.
re?
8
Matches 0 or 1 occurrence of preceding expression.
re{ n}
9
Matches exactly n number of occurrences of preceding expression.
re{ n,}
10
Matches n or more occurrences of preceding expression.
re{ n, m}
11
Matches at least n and at most m occurrences of preceding expression.
a| b
12
Matches either a or b.
(re)
13
Groups regular expressions and remembers matched text.
(?imx)
57
(?-imx)
(?: re)
16
Groups regular expressions without remembering matched text.
(?imx: re)
17
Temporarily toggles on i, m, or x options within parentheses.
(?-imx: re)
18
Temporarily toggles off i, m, or x options within parentheses.
(?#...)
19
Comment.
(?= re)
20
Specifies position using a pattern. Doesn't have a range.
(?! re)
21
Specifies position using pattern negation. Doesn't have a range.
(?> re)
22
Matches independent pattern without backtracking.
\w
23
Matches word characters.
58
\W
24
Matches nonword characters.
\s
25
Matches whitespace. Equivalent to [\t\n\r\f].
\S
26
Matches nonwhitespace.
\d
27
Matches digits. Equivalent to [0-9].
\D
28
Matches nondigits.
\A
29
Matches beginning of string.
\Z
30
Matches end of string. If a newline exists, it matches just before newline.
\z
31
Matches end of string.
\G
32
Matches point where last match finished.
33 \b
59
Matches word boundaries when outside brackets. Matches backspace (0x08)
when inside brackets.
\B
34
Matches nonword boundaries.
\1...\9
36
Matches nth grouped subexpression.
\10
Regular Expression
Literal characters
python
1
Match "python".
Character classes
[Pp]ython
1
Match "Python" or "python"
60
rub[ye]
2
Match "ruby" or "rube"
[aeiou]
3
Match any one lowercase vowel
[0-9]
4
Match any digit; same as [0123456789]
[a-z]
5
Match any lowercase ASCII letter
[A-Z]
6
Match any uppercase ASCII letter
[a-zA-Z0-9]
7
Match any of the above
[^aeiou]
8
Match anything other than a lowercase vowel
[^0-9]
9
Match anything other than a digit
1 .
61
Match any character except newline
\d
2
Match a digit: [0-9]
\D
3
Match a nondigit: [^0-9]
\s
4
Match a whitespace character: [ \t\r\n\f]
\S
5
Match nonwhitespace: [^ \t\r\n\f]
\w
6
Match a single word character: [A-Za-z0-9_]
\W
7
Match a nonword character: [^A-Za-z0-9_]
Repetition Cases
ruby?
1
Match "rub" or "ruby": the y is optional
ruby*
2
Match "rub" plus 0 or more ys
62
ruby+
3
Match "rub" plus 1 or more ys
\d{3}
4
Match exactly 3 digits
\d{3,}
5
Match 3 or more digits
\d{3,5}
6
Match 3, 4, or 5 digits
Nongreedy repetition
<.*>
1
Greedy repetition: matches "<python>perl>"
<.*?>
2
Nongreedy: matches "<python>" in "<python>perl>"
1 \D\d+
63
No group: + repeats \d
(\D\d)+
2
Grouped: + repeats \D\d pair
([Pp]ython(, )?)+
3
Match "Python", "Python, python, python", etc.
Backreferences
([Pp])ython&\1ails
1
Match python&pails or Python&Pails
(['"])[^\1]*\1
Alternatives
python|perl
1
Match "python" or "perl"
2 rub(y|le))
64
Match "ruby" or "ruble"
Python(!+|\?)
3
"Python" followed by one or more ! or one ?
Anchors
^Python
1
Match "Python" at the start of a string or internal line
Python$
2
Match "Python" at the end of a string or line
\APython
3
Match "Python" at the start of a string
Python\Z
4
Match "Python" at the end of a string
\bPython\b
5
Match "Python" at a word boundary
\brub\B
6
\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
65
Python(?=!)
7
Match "Python", if followed by an exclamation point.
Python(?!!)
8
Match "Python", if not followed by an exclamation point.
R(?#comment)
1
Matches "R". All the rest is a comment
R(?i)uby
2
Case-insensitive while matching "uby"
R(?i:uby)
3
Same as above
rub(?:y|le))
4
Group only without creating \1 backreference
Python Exception Handling allows a program to gracefully handle unexpected events (like
invalid input or missing files) without crashing. Instead of terminating abruptly, Python lets
you detect the problem, respond to it, and continue execution when possible.
Exception Handling in Python is a mechanism that allows you to handle errors in a controlled
way — instead of your program crashing when an error occurs.
66
It helps make programs robust and user-friendly by detecting and responding to runtime errors
gracefully.
What Is an Exception?
An exception is an error that occurs during the execution of a program, interrupting its normal
flow.
Exception Cause
Basic Syntax
try:
except ExceptionType:
Errors and exceptions are both issues in a program, but they differ in severity and handling. Let's
see how:
67
• Error: Serious problems in the program logic that cannot be handled. Examples include
syntax errors or memory errors.
• Exception: Less severe problems that occur at runtime and can be managed using
exception handling (e.g., invalid input, missing files).
Python provides four main keywords for handling exceptions: try, except, else and finally each
plays a unique role. Let's see syntax:
try:
# Code
except SomeException:
# Code
else:
# Code
finally:
# Code
• finally: Runs regardless of what happens useful for cleanup tasks like closing files.
68
2. Catching Multiple Exceptions
We can catch multiple exceptions in a single block if we need to handle them in the same way or
we can separate them if different types of exceptions require different handling.
3. Catch-All Handlers and Their Risks
Sometimes we may use a catch-all handler to catch any exception, but it can hide useful
debugging info.
Raise an Exception
We raise an exception in Python using the raise keyword followed by an instance of the exception
class that we want to trigger. We can choose from built-in exceptions or define our own custom
exceptions by inheriting from Python's built-in Exception class.
Custom Exceptions
You can also create custom exceptions by defining a new class that inherits from Python’s built-in
Exception class. This is useful for application-specific errors.
Advantages
Disadvantages
Exception handling have some cons as well which are listed below:
69
Exceptions in Python
An exception can be defined as an abnormal condition in a program. It interrupts the flow of the
program. Whenever an exception occurs, the program halts the execution, and thus the further
code is not executed.
In general an exception is an error that happens during execution of a program. When that error
occurs, it terminates program execution. In Python, an error can be a syntax error or an exception.
Now we will see what an exception is and how it differs from a syntax error.
[Link]
a=5
b=0
print(a/b))
Output:
The arrow indicates where the parser ran into the syntax error. In this example, there was one
more bracket. Remove it and run your code again
[Link]
a=5
b=0
print(a/b)
Output:
70
File "[Link]", line 3, in
print(a/b)
ZeroDivisionError: division by zero
This time, the parser ran into an exception error. This type of error occurs whenever syntactically
correct Python code results in an error. The last line of the message indicated what type of
exception error you ran into.
Instead of showing the message exception error, Python details what type of exception error was
encountered. In this case, it was a ZeroDivisionError.
Python supports various built-in exceptions, the commonly used exceptions are
• NameError: It occurs when a name is not found.i.e attempt to access an undeclared variable
Example:
a=5
c=a+b
print("Sum =",c)
Output:
Example:
a=5
b=0
print(a/b)
Output:
71
File "[Link]", line 3, in
print(a/b)
ZeroDivisionError: division by zero
Example:
Output:
Enter a number : 23
Enter a number : abc
Traceback (most recent call last):
File "[Link]", line 2, in
b=int(input("Enter a number : "))
ValueError: invalid literal for int() with base 10: 'abc'
Example:
ls=['c','java','python']
print("list item is :",ls[5])
Output:
Example:
dic={"name":"Madhu","location":"Hyd"}
72
print("The age is :",dic["age"])
Output:
Example:
fn=open("[Link]")
print(fn)
Output:
Exceptions as Strings
Prior to Python 1.5, standard exceptions were implemented as strings. However, this became
limiting in that it did not allow for exceptions to have relationships to each other. As of python 1.5,
all standard exceptions are now classes. It is still possible for programmers to generate their own
exceptions as strings, but we recommend using exception classes from now on.
Python 2.5 begins the process of deprecating string exceptions from Python forever. In 2.5, raise
of string exceptions generates a warning. In 2.6, the catching of string exceptions results in a
warning. Since they are rarely used and are being deprecated, we will no longer consider string
exceptions.
Creating Exceptions
Python allow programmers to create their own exception class. Exceptions should typically be
derived from the Exception class, either directly or indirectly.
73
Exception handling in Python
Python provides us with the way to handle the Exception so that the other part of the code can be
executed without any interrupt.
• try
• except
• finally
• raise
• assert
If the python program contains suspicious code that may throw the exception, we must place that
code in the try block. The try block must be followed with the except statement which contains a
block of code that will be executed if there is some exception in the try block.
Syntax:
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
Example:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
74
c = a/b;
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
#other code:
print("other part of the program")
Output: Case 1
Enter a:23
Enter b:3
a/b = 7
other part of the program
Output: Case 2
Enter a:3
Enter b:0
can't divide by zero
other part of the program
Output: Case 3
Enter a:34
Enter b:abc
can't divide by zero
other part of the program
We can also use the else statement with the try-except statement in which, we can place the code
which will be executed if no exception occurs in the try block.
Syntax:
try:
#block of code
75
except Exception1:
#block of code
else:
#this code executes if no except block is executed
Example:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
else:
print("code for else block")
#other code:
print("other part of the program")
Output: Case 1
Enter a:21
Enter b:3
a/b = 7
code for else block
other part of the program
Output: Case 2
Enter a:3
Enter b:0
can't divide by zero
other part of the program
Output: Case 3
Enter a:3
76
Enter b:df
can't divide by zero
other part of the program
finally statement
We can use the finally block with the try block in which, we can place the important code which
must be executed either try throws an exception or not.
Syntax:
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
finally:
# this code will always be executed
Example:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
77
print("a/b = %d"%c)
except ZeroDivisionError:
print("can't divide by zero")
except ValueError:
print("Enter Numbers only")
else:
print("code for else block")
finally:
print("Imp code-always executes")
Output: Case 1
Enter a:24
Enter b:4
a/b = 6
code for else block
Imp code-always executes
Output: Case 2
Enter a:3
Enter b:0
can't divide by zero
Imp code-always executes
Output: Case 3
Enter a:36
Enter b:abc
Enter Numbers only
Imp code-always executes
78
We can use raise to throw an exception if a condition occurs. i.e. If you want to throw an error
when a certain condition occurs we can use raise keyword.
Syntax:
raise Exception_class
Example:
try:
age = int(input("Enter the age : "))
if age<18:
raise Exception;
else:
print("the age is valid")
except Exception:
print("The age is not valid")
Output: Case 1
Output: Case 2
Example:
try:
a = int(input("Enter a : "))
b = int(input("Enter b : "))
if b is 0:
raise ArithmeticError;
else:
print("a/b = ",a/b)
79
except ValueError:
print("The values must be numbers")
except ArithmeticError:
print("The value of b can't be 0")
Output: Case 1
Enter a : 34
Enter b : 12
a/b = 2.8333333333333335
Output: Case 2
Enter a : 22
Enter b : 0
The value of b can't be 0
Output: Case 2
Enter a : 22
Enter b : sdf
The values must be numbers
Assertions are statements that assert or state a fact confidently in your program. For example,
while writing a division function, you're confident the divisor shouldn't be zero, you assert divisor is
not equal to zero. Assertions are simply Boolean expressions that checks if the conditions return
true or not. If it is true, the program does nothing and moves to the next line of code. However, if
it's false, the program stops and throws an error. It is also a debugging tool as it brings the
program on halt as soon as any error occurred and shows on which point of the program error has
occurred.
80
assert Statement
Python has built-in assert statement to use assertion condition in the program. assert statement
has a condition or expression which is supposed to be always true. If the condition is false assert
halts the program and gives an AssertionError.
Syntax:
1. assert statement has a condition and if the condition is not satisfied the program will stop
and give AssertionError.
2. assert statement can also have a condition and a optional error message. If the condition is
not satisfied assert stops the program and gives AssertionError along with the error
message.
Example:
def avg(marks):
assert len(marks) != 0,"The List is empty."
return sum(marks)/len(marks)
marks1 = [67,59,86,75,92]
print("The Average of Marks1:",avg(marks1))
marks2 = []
81
print("The Average of Marks2:",avg(marks2))
Output:
In the above example, we have passed a non-empty list marks1 and an empty list marks2 to the
avg() function. We received an output for marks1 list successfully, but after that, we got an error
AssertionError: List is empty.
The assert condition is satisfied by the marks1 list and lets the program to continue to run.
However, marks2 doesn't satisfy the condition and gives an AssertionError.
Example:
x = int(input("Enter x :"))
y = int(input("Enter y :"))
# It uses assert to check for 0
print ("x / y value is : ")
assert y != 0, "Divide by 0 error"
Output: Case 1
Enter x :33
Enter y :11
x / y value is :
3.0
Output: Case 2
Enter x :33
Enter y :0
x / y value is :
AssertionError: Divide by 0 error
82
Python OOP Concepts
OOP is a way of organizing code that uses objects and classes to represent real-world entities and
their behavior. In OOP, object has attributes thing that has specific data and can perform certain
actions using methods.
Python supports the core principles of object-oriented programming, which are the building blocks
for designing robust and reusable software. The diagram below demonstrates these core
principles:
1. Class
A class is a collection of objects. Classes are blueprints for creating objects. A class defines a
set of attributes and methods that the created objects (instances) can have.
Some points on Python class:
83
• Classes are created by keyword class.
• Attributes are the variables that belong to a class.
• Attributes are always public and can be accessed using the dot (.) operator. Example:
[Link]
Creating a Class
Here, class keyword indicates that we are creating a class followed by name of the class (Dog in
this case).
class Dog:
species = "Canine" # Class attribute
Self-Parameter
Self-parameter is a reference to the current instance of the class. It allows us to access the
attributes and methods of the object.
84
__init__ Method
__init__ method is the constructor in Python, automatically called when a new object is created.
It initializes the attributes of the class.
Explanation:
• __init__: Special method used for initialization.
• [Link] and [Link]: Instance attributes initialized in the constructor.
3. Inheritance
Inheritance allows a class (child class) to acquire properties and methods of another class
(parent class). It supports hierarchical classification and promotes code reuse.
85
Types of Inheritance:
1. Single Inheritance: A child class inherits from a single parent class.
2. Multiple Inheritance: A child class inherits from more than one parent class.
3. Multilevel Inheritance: A child class inherits from a parent class, which in turn inherits
from another class.
4. Hierarchical Inheritance: Multiple child classes inherit from a single parent class.
5. Hybrid Inheritance: A combination of two or more types of inheritance.
Explanation:
• Single Inheritance: Labrador inherits Dog's attributes and methods.
• Multilevel Inheritance: GuideDog extends Labrador, inheriting both Dog and
Labrador functionalities.
• Multiple Inheritance: GoldenRetriever inherits from both Dog and Friendly.
4. Polymorphism
Polymorphism in Python means "same operation, different behavior." It allows functions or
methods with the same name to work differently depending on the type of object they are acting
upon.
Types of Polymorphism
1. Compile-Time Polymorphism:
86
This type of polymorphism is determined during the compilation of the program. It allows
methods or operators with the same name to behave differently based on their input parameters
or usage. In languages like Java or C++, compile-time polymorphism is achieved through
method overloading but it's not directly supported in Python.
In Python:
• True compile-time polymorphism is not supported.
• Instead, Python mimics it using default arguments or *args/**kwargs.
• Operator overloading can also be seen as part of polymorphism, though it is
implemented at runtime in Python.
2. Run-Time Polymorphism
Run-Time Polymorphism is determined during the execution of the program. It covers multiple
forms in Python:
• Method Overriding: A subclass redefines a method from its parent class.
• Duck Typing: If an object implements the required method, it works regardless of its
type.
• Operator Overloading: Special methods (__add__, __sub__, etc.) redefine how
operators behave for user-defined objects.
Explanation:
• Method Overriding: Dog class overrides the speak method from the parent Animal
class. This allows the program to call the speak method on a Dog object and get a
specialized "Woof!" response, which is determined at runtime.
• Duck Typing: "make_animal_speak" function can accept both a Dog and a Cat object.
It doesn't care about their class hierarchy; it only checks if they have a speak method,
showcasing Python's flexible typing.
• Operator Overloading: "__add__" method within the Vector class is a special method
that defines how the + operator behaves for Vector objects. This allows the user to add
two vectors using the familiar + symbol, which is a form of syntactic sugar.
5. Encapsulation
Encapsulation is the bundling of data (attributes) and methods (functions) within a class,
restricting access to some components to control interactions.
A class is an example of encapsulation as it encapsulates all the data that is member functions,
variables, etc.
87
Types of Encapsulations:
1. Public Members: Accessible from anywhere.
2. Protected Members: Accessible within the class and its subclasses.
3. Private Members: Accessible only within the class.
Explanation:
• Public Members: Easily accessible, such as name.
• Protected Members: Used with a single _, such as _breed. Access is discouraged but
allowed in subclasses.
• Private Members: Used with __, such as __age. Access requires getter and setter
methods.
6. Data Abstraction
Abstraction hides the internal implementation details while exposing only the necessary
functionality. It helps focus on "what to do" rather than "how to do it."
Types of Abstraction:
• Partial Abstraction: Abstract class contains both abstract and concrete methods.
• Full Abstraction: Abstract class contains only abstract methods (like interfaces).
Explanation:
• Partial Abstraction: The Dog class has both abstract (sound) and concrete
(display_name) methods.
• Why Use It: Abstraction ensures consistency in derived classes by enforcing the
implementation of abstract methods.
88