[Go to site: main page, start]

0% found this document useful (0 votes)
23 views88 pages

Comprehensive Python Programming Guide

Python is a versatile and widely-used programming language known for its simplicity and readability, making it suitable for both beginners and experienced developers. It supports multiple programming paradigms, including procedural and object-oriented programming, and has a rich ecosystem of libraries and frameworks for various applications such as web development, data science, and machine learning. Python's history dates back to the late 1980s, and it has evolved significantly, becoming the most popular programming language in the tech industry.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views88 pages

Comprehensive Python Programming Guide

Python is a versatile and widely-used programming language known for its simplicity and readability, making it suitable for both beginners and experienced developers. It supports multiple programming paradigms, including procedural and object-oriented programming, and has a rich ecosystem of libraries and frameworks for various applications such as web development, data science, and machine learning. Python's history dates back to the late 1980s, and it has evolved significantly, becoming the most popular programming language in the tech industry.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming in Python

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

Python is a general-purpose, dynamically typed, high-level, compiled and interpreted, garbage-


collected, and purely object-oriented programming language that supports procedural, object-
oriented, and functional programming.

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.

Python Basic Syntax

There is no use of curly braces or semicolons in Python programming language. It is an English-


like language. But Python uses indentation to define a block of code. Indentation is nothing but
adding whitespace before the statement when it is needed.

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

Python is a general-purpose, popular programming language, and it is used in almost every


technical field. The various areas of Python use are given below.

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 Frameworks and Libraries

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.

o Web development (Server-side) - Django Flask, Pyramid, CherryPy


o GUIs based applications - Tkinter, PyGTK, PyQt, PyJs, etc.
o Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
o Mathematics - NumPy, Pandas, etc.
o BeautifulSoup: a library for web scraping and parsing HTML and XML
o Requests: a library for making HTTP requests
o SQLAlchemy: a library for working with SQL databases
o Kivy: a framework for building multi-touch applications
o Pygame: a library for game development

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.

Introduction to 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.

Advantages of Using Comments

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.

Below are some of the most common uses for comments:

o Readability of the Code


o Restrict code execution
o Provide an overview of the program or project metadata
o To add resources to the code

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.

Introducing Python Keywords

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.

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

9
assert del global not with

async elif if or yield

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.

Rules for Keywords in Python

• Python keywords cannot be used as identifiers.


• All the keywords in Python should be in lowercase except True and False.

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.

Rules for Naming Python Identifiers

• It cannot be a reserved python keyword.


• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an underscore ( _ ).

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.

Example of Variable in Python

An Example of a Variable in Python is a representational name that serves as a pointer to an


object. Once an object is assigned to a variable, it can be referred to by that name. In layman’s
terms, we can say that Variable in Python is containers that store values. Here we have stored

11
“Geeksforgeeks” in a variable var, and when we call its name the stored information will get
printed.

• The value stored in a variable can be changed during program execution.


• A Variable in Python is only a name given to a memory location, all the operations done on
the variable effects that memory location.

Rules for Python variables

• 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.

o The variable's first character must be an underscore or alphabet (_).


o Every one of the characters with the exception of the main person might be a letter set of
lower-case(a-z), capitalized (A-Z), highlight, or digit (0-9).
o White space and special characters (!, @, #, %, etc.) are not allowed in the identifier name.
^, &, *).
o Identifier name should not be like any watchword characterized in the language.
o Names of identifiers are case-sensitive; for instance, my name, and MyName isn't
something very similar.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

12
Declaring Variable and Assigning Values

o Python doesn't tie us to pronounce a variable prior to involving it in the application. It


permits us to make a variable at the necessary time.
o In Python, we don't have to explicitly declare variables. The variable is declared
automatically whenever a value is added to it.
o The equal (=) operator is utilized to assign worth to a variable.

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.

Different Forms of Assignment Statements in Python

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.

There are some important properties of assignment in Python :-

• Assignment creates object references instead of copying the objects.


• Python creates a variable name the first time when they are assigned a value.
• Names must be assigned before being referenced.
• There are some operations that perform assignments implicitly.

Assignment statement forms :-

1. Basic form:

This form is the most common form.

student = 'Geeks'

print(student)

13
2. Tuple assignment:

# equivalent to: (x, y) = (50, 100)

x, y = 50, 100

print('x = ', x)

print('y = ', y)

3. List assignment:

This works in the same way as the tuple assignment.

[x, y] = [2, 4]

print('x = ', x)

print('y = ', y)

Python Data Types

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.

1. Numeric Data Types in Python

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.

2. Sequence Data Types in Python

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

• Sequence: String, list, and tuple

• Set

• Dictionary (dict)

To check the data type of variable use the built-in function type() and isinstance().

• The type() function returns the data type of the variable

• The isinstance() function checks whether an object belongs to a particular class.

In this article, we will learn the following Python data types in detail.

Data type Description Example

int To store integer values n = 20

float To store decimal values n = 20.75

complex To store complex numbers (real and imaginary part) n = 10+20j

str To store textual/string data name = 'Jessa'

bool To store boolean values flag = True

list To store a sequence of mutable data l = [3, 'a', 2.5]

tuple To store sequence immutable data t =(2, 'b', 6.4)

dict To store key: value pair d = {1:'J', 2:'E'}

set To store unorder and unindexed values s = {1, 3, 5}

frozenset To store immutable version of the set f_set=frozenset({5,7})

range To generate a sequence of number numbers = range(10)

bytes To store bytes values b=bytes([5,10,15,11])

Str data type

In Python, A string is a sequence of characters enclosed within a single quote or double


quote. These characters could be anything like letters, numbers, or special symbols enclosed
within double quotation marks. For example, "PYnative" is a string.

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.

Int data type

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

1. Directly assigning an integer value to a variable


2. Using a int() class.

You can also store integer values other than base 10 such as

• Binary (base 2)

• Octal (base 8)

• Hexadecimal numbers (base 16)

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.

The float type in Python is represented using a float class.

We can create a float variable using the two ways

1. Directly assigning a float value to a variable


2. Using a float() class.

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

A complex number is a number with a real and an imaginary component represented


as a+bj where a and b contain integers or floating-point values.

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.

List data type

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

We can create a list using the two ways

1. By enclosing elements in the square brackets [].


2. Using a list() class.

Tuple data type

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.

We can create a tuple using the two ways

1. By enclosing elements in the parenthesis ()


2. Using a tuple() class.

Dict data type

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.

Dictionary has some characteristics which are listed below:

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

We can create a dictionary using the two ways

1. By enclosing key and values in the curly brackets {}


2. Using a dict() class.

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.

The Set data type in Python is represented using a set class.

We can create a Set using the two ways

1. By enclosing values in the curly brackets {}


2. Using a set() class.

The set data type has the following characteristics.

1. It is mutable which means we can change set items


2. Duplicate elements are not allowed
3. Heterogeneous (values of all data types) elements are allowed
4. Insertion order of elements is not preserved, so we can’t perform indexing on a Set

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.

Use a frozenset() class to create a frozenset.

Bool data type

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.

Range data type

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

** (Exponent) As it calculates the first operand's power to the second operand, it is an


exponent operator.

// (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 -

1. a = 32 # Initialize the value of a


2. b = 6 # Initialize the value of b
3. print('Addition of two numbers:',a+b)
4. print('Subtraction of two numbers:',a-b)
5. print('Multiplication of two numbers:',a*b)
6. print('Division of two numbers:',a/b)
7. print('Reminder of two numbers:',a%b)
8. print('Exponent of two numbers:',a**b)

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 -

Addition of two numbers: 38


Subtraction of two numbers: 26
Multiplication of two numbers: 192
Division of two numbers: 5.333333333333333
Reminder of two numbers: 2
Exponent of two numbers: 1073741824
Floor division of two numbers: 5

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 -

1. a = 32 # Initialize the value of a


2. b = 6 # Initialize the value of b
3. print('Two numbers are equal or not:',a==b)
4. print('Two numbers are not equal or not:',a!=b)
5. print('a is less than or equal to b:',a<=b)
6. print('a is greater than or equal to b:',a>=b)
7. print('a is greater b:',a>b)
8. print('a is less than 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 -

Two numbers are equal or not: False


Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False

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

= It assigns the value of the right expression to the left operand.

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 -

1. a = 32 # Initialize the value of a


2. b = 6 # Initialize the value of b
3. print('a=b:', a==b)
4. print('a+=b:', a+b)
5. print('a-=b:', a-b)
6. print('a*=b:', a*b)
7. print('a%=b:', a%b)
8. print('a**=b:', a**b)
9. print('a//=b:', a//b)

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 -

1. a = 5 # initialize the value of a


2. b = 6 # initialize the value of b
3. print('a&b:', a&b)
4. print('a|b:', a|b)
5. print('a^b:', a^b)

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 -

1. a = 5 # initialize the value of a

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 -

Is this statement true?: False


Any one statement is true?: True
Each statement is true then return False and vice-versa: True

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

in If the first operand cannot be found in the second operand, it is evaluated to be


true (list, tuple, or dictionary).

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 -

Is value Present? True


Is value not Present? True

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

** Overall other operators employed in the expression, the exponent operator


is given precedence.

~+- the minus, unary plus, and negation.

* / % // the division of the floor, the modules, the division, and the multiplication.

+- Binary plus, and minus

>> << Left shift. and right shift

& Binary and.

^| Binary xor, and or

<= < > >= Comparison operators (less than, less than equal to, greater than, greater
then equal to).

<> == != Equality operators.

= %= /= //= -= += Assignment operators


*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

33
Python Built in Functions

Python has a set of built-in functions.

Function Description

abs() Returns the absolute value of a number

all() Returns True if all items in an iterable object are


true

any() Returns True if any item in an iterable object is


true

ascii() Returns a readable version of an object.


Replaces none-ascii characters with escape
character

bin() Returns the binary version of a number

bool() Returns the boolean value of the specified object

bytearray() Returns an array of bytes

bytes() Returns a bytes object

callable() Returns True if the specified object is callable,

34
otherwise False

chr() Returns a character from the specified Unicode


code.

classmethod() Converts a method into a class method

compile() Returns the specified source as an object, ready


to be executed

complex() Returns a complex number

delattr() Deletes the specified attribute (property or


method) from the specified object

dict() Returns a dictionary (Array)

dir() Returns a list of the specified object's properties


and methods

divmod() Returns the quotient and the remainder when


argument1 is divided by argument2

enumerate() Takes a collection (e.g. a tuple) and returns it as


an enumerate object

eval() Evaluates and executes an expression

35
exec() Executes the specified code (or object)

filter() Use a filter function to exclude items in an


iterable object

float() Returns a floating point number

format() Formats a specified value

frozenset() Returns a frozenset object

getattr() Returns the value of the specified attribute


(property or method)

globals() Returns the current global symbol table as a


dictionary

hasattr() Returns True if the specified object has the


specified attribute (property/method)

hash() Returns the hash value of a specified object

help() Executes the built-in help system

hex() Converts a number into a hexadecimal value

id() Returns the id of an object

36
input() Allowing user input

int() Returns an integer number

isinstance() Returns True if a specified object is an instance


of a specified object

issubclass() Returns True if a specified class is a subclass of


a specified object

iter() Returns an iterator object

len() Returns the length of an object

list() Returns a list

locals() Returns an updated dictionary of the current


local symbol table

map() Returns the specified iterator with the specified


function applied to each item

max() Returns the largest item in an iterable

memoryview() Returns a memory view object

min() Returns the smallest item in an iterable

37
next() Returns the next item in an iterable

object() Returns a new object

oct() Converts a number into an octal

open() Opens a file and returns a file object

ord() Convert an integer representing the Unicode of


the specified character

pow() Returns the value of x to the power of y

print() Prints to the standard output device

property() Gets, sets, deletes a property

range() Returns a sequence of numbers, starting from 0


and increments by 1 (by default)

repr() Returns a readable version of an object

reversed() Returns a reversed iterator

round() Rounds a numbers

set() Returns a new set object

38
setattr() Sets an attribute (property/method) of an object

slice() Returns a slice object

sorted() Returns a sorted list

staticmethod() Converts a method into a static method

str() Returns a string object

sum() Sums the items of an iterator

super() Returns an object that represents the parent


class

tuple() Returns a tuple

type() Returns the type of an object

vars() Returns the __dict__ property of an object

zip() Returns an iterator, from two or more iterators

Python String Methods

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.

Case Changing of Python String Methods

The below Python functions are used to change the case of the strings. Let’s look at some
Python string methods with examples:

1. lower(): Converts all uppercase characters in a string into lowercase


2. upper(): Converts all lowercase characters in a string into uppercase
3. title(): Convert string to title case
4. swapcase(): Swap the cases of all characters in a string
5. capitalize(): Convert the first character of a string to uppercase

Example: Changing the case of Python String Methods

List of String Methods in Python


Here is the list of in-built Python string methods, that you can use to perform actions on string:

Function Name Description

capitalize() Converts the first character of the string to a capital (uppercase) letter

casefold() Implements caseless string matching

center() Pad the string with the specified character.

count() Returns the number of occurrences of a substring in the string.

encode() Encodes strings with the specified encoded scheme

40
Function Name Description

endswith() Returns “True” if a string ends with the given suffix

Specifies the amount of space to be substituted with the “\t” symbol in the
expandtabs()
string

find() Returns the lowest index of the substring if it is found

format() Formats the string for printing it to console

format_map() Formats specified values in a string using a dictionary

index() Returns the position of the first occurrence of a substring in a string

isalnum() Checks whether all the characters in a given string is alphanumeric or not

isalpha() Returns “True” if all characters in the string are alphabets

isdecimal() Returns true if all characters in a string are decimal

isdigit() Returns “True” if all characters in the string are digits

isidentifier() Check whether a string is a valid identifier or not

islower() Checks if all characters in the string are lowercase

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

istitle() Returns “True” if the string is a title cased string

isupper() Checks if all characters in the string are uppercase

join() Returns a concatenated String

ljust() Left aligns the string according to the width specified

lower() Converts all uppercase characters in a string into lowercase

lstrip() Returns the string with leading characters removed

maketrans() Returns a translation table

partition() Splits the string at the first occurrence of the separator

replace() Replaces all occurrences of a substring with another substring

rfind() Returns the highest index of the substring

rindex() Returns the highest index of the substring inside the string

rjust() Right aligns the string according to the width specified

rpartition() Split the given string into three parts

rsplit() Split the string from the right by the specified separator

rstrip() Removes trailing characters

splitlines() Split the lines at line boundaries

42
Function Name Description

startswith() Returns “True” if a string starts with the given prefix

strip() Returns the string with both leading and trailing characters

swapcase() Converts all uppercase characters to lowercase and vice versa

title() Convert string to title case

translate() Modify string according to given translation mappings

upper() Converts all lowercase characters in a string into uppercase

Returns a copy of the string with ‘0’ characters padded to the left side of
zfill()
the string

Conditional Statements in Python


Understanding and mastering Python’s conditional statements is fundamental for any
programmer aspiring to write efficient and robust code. In this guide, we’ll delve into the
intricacies of conditional statements in Python, covering the basics, advanced techniques, and
best practices.
What are Conditional Statements?
Conditional Statements are statements in Python that provide a choice for the control flow based
on a condition. It means that the control flow of the Python program will be decided based on the
outcome of the condition.
Now let us see how Conditional Statements are implemented in Python.
Types of Conditional Statements in Python

1. If Conditional Statement in Python


If the simple code of block is to be performed if the condition holds then the if statement is used.
Here the condition mentioned holds then the code of the block runs otherwise not.
Syntax of If Statement:

43
if condition:
# Statements to execute if
# condition is true

• Python

# if statement example

if 10 > 5:

print("10 greater than 5")

print("Program ended")

Output
10 greater than 5

Program ended

2. If else Conditional Statements in Python


In a conditional if Statement the additional block of code is merged as an else statement which is
performed when if condition is false.
Syntax of Python If-Else:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

• Python

# if..else statement example

44
x=3

if x == 4:

print("Yes")

else:

print("No")

Output
No

3. Nested if..else Conditional Statements in Python


Nested if..else means an if-else statement inside another if statement. Or in simple words first,
there is an outer if statement, and inside it another if – else statement is present and such type of
statement is known as nested if statement. We can use one if or else if statement inside another
if or else if statements.

• Python

# if..else chain statement

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:

print("letter isn't A, B and C")

Output
letter is A

4. If-elif-else Conditional Statements in Python


The if statements are executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final “else” statement will be executed.

• Python

# if-elif statement example

letter = "A"

if letter == "B":

print("letter is B")

elif letter == "C":

print("letter is C")

46
elif letter == "A":

print("letter is A")

else:

print("letter isn't A, B or C")

Output
letter is A

5. Ternary Expression Conditional Statements in Python


The Python ternary Expression determines if a condition is true or false and then returns the
appropriate value in accordance with the result. The ternary Expression is useful in cases where
we need to assign a value to a variable based on a simple condition, and we want to keep our
code more concise — all in just one line of code.
Syntax of Ternary Expression
Syntax: [on_true] if [expression] else [on_false]
expression: conditional_expression | lambda_expr

• Python

# Python program to demonstrate nested ternary operator

a, b = 10, 20

print ("Both a and b are equal" if a == b else "a is greater than b"

if a > b else "b is greater than a")

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

• A Regular Expression (RegEx) is a pattern that describes a set of


strings.

• It is mainly used for:

o Searching text

o Validating inputs

o Extracting substrings

o Replacing or splitting strings based on patterns

In Python, regular expressions are supported through the built-in re


module.

2. The re Module

To use regular expressions in Python:

import re

3. Common re Module Functions

Function Description Example

Matches the pattern


[Link](pattern, [Link]('Py', 'Python')
only at the beginning of
string) ✅
the string.

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.

Here's a complete list of the metacharacters −

.^$*+?{}[]\|()

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 '-'.

[Link]. Metacharacters & Description

[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 –

[Link]. Metacharacters & Description

\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].

3 \sMatches any whitespace character; this is equivalent to the class [\t\n\r\f\v].

\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.

The [Link]() Function

This function attempts to match RE pattern at the start of string with optional flags. Following is
the syntax for this function −

[Link](pattern, string, flags=0)

Here is the description of the parameters −

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.

If the pattern is not found, the match object is None.

We use group(num) or groups() function of match object to get matched expression.

[Link]. Match Object Methods & Description

1 group(num=0)This method returns entire match (or specific subgroup num)

groups()This method returns all matching subgroups in a tuple (empty if there weren't
2
any)

[Link]. Parameter & Description

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.

The [Link] function returns a match object on success, none on failure. We


use group(num) or groups() function of match object to get the matched expression.

[Link]. Match Object Methods & Description

1 group(num=0)This method returns entire match (or specific subgroup num)

groups()This method returns all matching subgroups in a tuple (empty if there


2
weren't any)

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

[Link]. Parameter & Description

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

[Link]. Modifier & Description

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

6 Permits "cuter" regular expression syntax. It ignores whitespace (except inside a


set [] or when escaped by a backslash) and treats unescaped # as a comment
marker.

Regular Expression Patterns

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 −

[Link]. Pattern & Description

^
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)

14 Temporarily toggles on i, m, or x options within a regular expression. If in


parentheses, only that area is affected.

57
(?-imx)

15 Temporarily toggles off i, m, or x options within a regular expression. If in


parentheses, only that area is affected.

(?: 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.

\n, \t, etc.


35
Matches newlines, carriage returns, tabs, etc.

\1...\9
36
Matches nth grouped subexpression.

\10

37 Matches nth grouped subexpression if it matched already. Otherwise refers to


the octal representation of a character code.

Regular Expression

Literal characters

[Link]. Example & Description

python
1
Match "python".

Character classes

[Link]. Example & Description

[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

Special Character Classes

[Link]. Example & Description

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

[Link]. Example & Description

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

This matches the smallest number of repetitions −

[Link]. Example & Description

<.*>
1
Greedy repetition: matches "<python>perl>"

<.*?>
2
Nongreedy: matches "<python>" in "<python>perl>"

Grouping with Parentheses

[Link]. Example & Description

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

This matches a previously matched group again −

[Link]. Example & Description

([Pp])ython&\1ails
1
Match python&pails or Python&Pails

(['"])[^\1]*\1

2 Single or double-quoted string. \1 matches whatever the 1st group matched. \2


matches whatever the 2nd group matched, etc.

Alternatives

[Link]. Example & Description

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

This needs to specify match position.

[Link]. Example & Description

^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.

Special Syntax with Parentheses

[Link]. Example & Description

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

Exception Handling in Python

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.

Examples of common exceptions:

Exception Cause

ZeroDivisionError Division by zero

ValueError Invalid value (e.g., converting "abc" to int)

TypeError Wrong data type used in an operation

IndexError Accessing an invalid list index

KeyError Accessing a non-existent dictionary key

FileNotFoundError Trying to open a file that doesn’t exist

Basic Syntax

try:

# Code that may cause an exception

except ExceptionType:

# Code to handle the exception

Difference Between Errors and Exceptions

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).

Syntax and Usage

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

• try: Runs the risky code that might cause an error.

• except: Catches and handles the error if one occurs.

• else: Executes only if no exception occurs in try.

• finally: Runs regardless of what happens useful for cleanup tasks like closing files.

• Python Catching Exceptions


• When working with exceptions in Python, we can handle errors more efficiently by
specifying the types of exceptions we expect. This can make code both safer and easier
to debug.
1. Catching Specific Exceptions
Catching specific exceptions makes code to respond to different exception types differently. It
precisely makes your code safer and easier to debug. It avoids masking bugs by only reacting to
the exact problems you expect.

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

Below are some benefits of using exception handling:

• Improved reliability: Programs don’t crash on unexpected input.

• Separation of concerns: Error-handling code stays separate from business logic.

• Cleaner code: Fewer conditional checks scattered in code.

• Helpful debugging: Tracebacks show exactly where the problem occurred.

Disadvantages

Exception handling have some cons as well which are listed below:

• Performance overhead: Handling exceptions is slower than simple condition checks.

• Added complexity: Multiple exception types may complicate code.

• Security risks: Poorly handled exceptions might leak sensitive details.

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.

Syntax errors occur when the parser detects an incorrect statement.

[Link]

a=5
b=0
print(a/b))

Output:

File "[Link]", line 3


print(a/b))
SyntaxError: invalid syntax

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:

Traceback (most recent call last):

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.

Standard Exceptions in Python

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:

Traceback (most recent call last):


File "[Link]", line 2, in
c=a+b
NameError: name 'b' is not defined

• ZeroDivisionError: Occurs when a number is divided by zero.

Example:

a=5
b=0
print(a/b)

Output:

Traceback (most recent call last):

71
File "[Link]", line 3, in
print(a/b)
ZeroDivisionError: division by zero

• ValueError: Occurs when an inappropriate value assigned to variable.

Example:

a=int(input("Enter a number : "))


b=int(input("Enter a number : "))
print("Sum =",a+b)

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'

• IndexError: Occurs when we request for an out-of-range index for sequence

Example:

ls=['c','java','python']
print("list item is :",ls[5])

Output:

Traceback (most recent call last):


File "[Link]", line 2, in
print("list item is :",ls[5])
IndexError: list index out of range.

• KeyError: Occurs when we request for a non-existent dictionary key

Example:

dic={"name":"Madhu","location":"Hyd"}

72
print("The age is :",dic["age"])

Output:

Traceback (most recent call last):


File "[Link]", line 2, in
print("The age is :",dic["age"])
KeyError: 'age'

• IOError: Occurs when we request for a non-existent input/output file.

Example:

fn=open("[Link]")
print(fn)

Output:

Traceback (most recent call last):


File "[Link]", line 1, in
fn=open("[Link]")
FileNotFoundError: [IOError] No such file or directory: '[Link]'

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.

For Exception handling, python uses following keywords or statements

• try

• except

• finally

• raise

• assert

try – except statement

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

try – except - else statement

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

raise & assert statements in Python

raise statement (or) Raising exceptions

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

Enter the age : 34


the age is valid

Output: Case 2

Enter the age : 12


The age is not valid

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

assert statement (or) Assertions

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:

assert condition [, error_message]

In Python we can use assert statement in two ways as mentioned above.

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:

The Average of Marks1: 75.8


AssertionError: The List is empty.

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

Object Oriented Programming is a fundamental concept in Python, empowering developers to


build modular, maintainable and scalable applications.

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.

Key Features of OOP in Python:

• Organizes code into classes and objects

• Supports encapsulation to group data and methods together

• Enables inheritance for reusability and hierarchy

• Allows polymorphism for flexible method implementation

• Improves modularity, scalability, and maintainability

Characteristics of OOP (Object Oriented Programming)

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

def __init__(self, name, age):


[Link] = name # Instance attribute
[Link] = age # Instance attribute
Explanation:
• class Dog: Defines a class named Dog.
• species: A class attribute shared by all instances of the class.
• __init__ method: Initializes the name and age attributes when a new object is
created.
2. Objects
An Object is an instance of a Class. It represents a specific implementation of the class and
holds its own data.
An object consists of:
• State: It is represented by the attributes and reflects the properties of an object.
• Behavior: It is represented by the methods of an object and reflects the response of
an object to other objects.
• Identity: It gives a unique name to an object and enables one object to interact with
other objects.
Creating Object
Creating an object in Python involves instantiating a class to create a new instance of that class.
This process is also referred to as object instantiation.

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.

Class and Instance Variables


In Python, variables defined in a class can be either class variables or instance variables, and
understanding the distinction between them is crucial for object-oriented programming.
Class Variables
These are the variables that are shared across all instances of a class. It is defined at the class
level, outside any methods. All objects of the class share the same value for a class variable
unless explicitly overridden in an object.
Instance Variables
Variables that are unique to each instance (object) of a class. These are defined within the
__init__ method or other instance methods. Each object maintains its own copy of instance
variables, independent of other objects.
Explanation:
• Class Variable (species): Shared by all instances of the class. Changing [Link]
affects all objects, as it's a property of the class itself.
• Instance Variables (name, age): Defined in the __init__ method. Unique to each
instance (e.g., [Link] and [Link] are different).
• Accessing Variables: Class variables can be accessed via the class name
([Link]) or an object ([Link]). Instance variables are accessed via the
object ([Link]).
• Updating Variables: Changing [Link] affects all instances. Changing
[Link] only affects dog1 and does not impact dog2.

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

You might also like