0% found this document useful (0 votes)
8 views

Cours Python Prohramming23

The document is a course outline for a Python Programming class at the University M’hamed Bougara of Boumerdes, led by Dr. Nekkaa. It covers various topics including getting started with Python, basic programming concepts, and object-oriented programming. The content is structured into sections with detailed subtopics, providing a comprehensive guide for students learning Python.

Uploaded by

chaoucheadem23
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)
8 views

Cours Python Prohramming23

The document is a course outline for a Python Programming class at the University M’hamed Bougara of Boumerdes, led by Dr. Nekkaa. It covers various topics including getting started with Python, basic programming concepts, and object-oriented programming. The content is structured into sections with detailed subtopics, providing a comprehensive guide for students learning Python.

Uploaded by

chaoucheadem23
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
You are on page 1/ 53

University M’hamed Bougara of Boumerdes

Faculty of Technology
Department of Electrical Systems Engineering

Python Programming

Lecturer: Dr.Nekkaa

Email: [email protected]

April 23, 2025


Contents

1 Getting Started with Python 1


1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 What is Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Interpreted vs. Compiled . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Python Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Anaconda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5.1 Versions of Anaconda . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Python Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Installing Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7.1 Python Windows Store App . . . . . . . . . . . . . . . . . . . . . . . 5
1.7.2 Installing Anaconda . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7.3 Installing Visual Studio Code . . . . . . . . . . . . . . . . . . . . . . 6
1.8 Start using Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.8.1 Python IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.8.2 My first Python program . . . . . . . . . . . . . . . . . . . . . . . . 6
1.8.3 Python Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.8.4 Running Python from the Console . . . . . . . . . . . . . . . . . . . 7
1.8.5 Scripting Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2 Basic Python Programming 11


2.1 Basic Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.1.1 Get Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2.1 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2.2 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2.3 String Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3 Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4 Python Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4.1 Importing Modules in Different Ways . . . . . . . . . . . . . . . . . . 15
2.5 Using Python Libraries, Packages, and Modules . . . . . . . . . . . . . . . . 16
2.5.1 Advantages and Disadvantages . . . . . . . . . . . . . . . . . . . . . 16
2.5.2 Important Python Libraries: . . . . . . . . . . . . . . . . . . . . . . . 16
2.5.3 Plotting in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

3 Python Programming 20
3.1 Conditional Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.1.1 If statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.1.2 If–else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.1.3 Chain multiple if statement . . . . . . . . . . . . . . . . . . . . . . . 22

i
CONTENTS ii

3.1.4 Nested if-else statement . . . . . . . . . . . . . . . . . . . . . . . . . 23


3.1.5 Using Logical Operators(and, or, not) in If Statements . . . . . . . . 23
3.2 Python Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.2.1 Creating a Python list . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.2.2 Length of a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2.3 Accessing items of a List . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2.4 Iterating a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.2.5 Adding elements to the list . . . . . . . . . . . . . . . . . . . . . . . 27
3.2.6 Modify the items of a List . . . . . . . . . . . . . . . . . . . . . . . 29
3.2.7 Modify all items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.2.8 Removing elements from a List . . . . . . . . . . . . . . . . . . . . . 29
3.2.9 Finding an element in the list . . . . . . . . . . . . . . . . . . . . . . 31
3.2.10 Concatenation of two lists . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.11 Copying a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.2.12 List operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.2.13 Python Built-in functions with List . . . . . . . . . . . . . . . . . . . 33
3.3 Creating Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.4 For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.4.1 Nested For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.5 While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.6 Break Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.7 Continue Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.8 Functions in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.8.1 Types of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.8.2 Creating a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.8.3 Create a Function in a separate File . . . . . . . . . . . . . . . . . . 38
3.8.4 Functions with multiple return values . . . . . . . . . . . . . . . . . . 39

4 Object Oriented Programming 40


4.1 What is Object Oriented Programming in Python . . . . . . . . . . . . . . . 40
4.2 Class and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.3 Class Attributes and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.4 Creating Class and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.5 Encapsulation in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.6 Inheritance In Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.6.1 Single Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.6.2 Hierarchical Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.6.3 Python super() function . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.6.4 Method Overriding . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.7 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
List of Figures

1.1 IDLE - Basic Python Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . 2


1.2 Python Shell/Python IDLE Editor . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Command Prompt Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4 Python Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.5 Running a Python Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6 Running Python Scripts from Console window . . . . . . . . . . . . . . . . . 9
1.7 Running a Python Script in Spyder . . . . . . . . . . . . . . . . . . . . . . . 10

2.1 Plotting in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

3.1 Python List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24


3.2 Python Positive and Negative indexing . . . . . . . . . . . . . . . . . . . . . 25

4.1 Python OOP concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

iii
Chapter 1

Getting Started with Python

1.1 Introduction
With this textbook, you will learn the fundamentals of Python programming. Python is a
powerful, easy-to-learn, and widely used programming language that is great for beginners
and professionals alike.
This course covers essential concepts such as variables, data types, loops, functions, and
object-oriented programming. It also includes numerous examples and self-paced exercises
that allow you to practice and apply what you learn at your own pace.
By the end of this course, you will have a solid foundation in Python and be able to write
your own programs, solve problems, and explore more advanced topics in programming.

1.2 What is Python?


Python is a widely used, open-source, and cross-platform programming language that has
seen significant growth in popularity over the last ten years. It was first released in 1991,
its latest version is 3.13.2. The primary and most commonly used implementation of Python
is CPython, which is written in C and serves as the official reference implementation of the
language.
Python is a versatile, multi-purpose programming language known for its extensive library
support. It is widely used in various fields such as:

• Scientific Computing: With libraries like NumPy, SciPy, and Pandas, Python excels
in data analysis, mathematical modeling, and scientific calculations.

• Simulations: Tools like SimPy and PyBullet make Python ideal for simulating systems
in areas like physics and robotics.

• Web Development: Frameworks like Django and Flask allow for the efficient develop-
ment of scalable and secure web applications.

The programming language is maintained and available from the Python Software Foun-
dation. You can download the basic Python features in one package, which includes the
Python programming language interpreter, a basic code editor, and an integrated develop-
ment environment (IDE), called IDLE. For more information, visit the official Python website
at https://www.python.org. See Figure 1.1 for reference.
But this is just the Python core, i.e., the interpreter, a very basic editor, and the minimum
needed to create basic Python programs.

1
CHAPTER 1. GETTING STARTED WITH PYTHON 2

Figure 1.1: IDLE - Basic Python Editor

Typically, you will need more features to solve your tasks. You can install and use separate
Python packages created by third parties. These packages need to be downloaded and installed
separately (typically using a tool called PIP), or you can choose to use a distribution package
like Anaconda.
Python is an object-oriented programming language (OOP), but you can use Python in
basic application without the need to know about or use the object-oriented features in Python.
Python is an interpreted programming language, this means that as a developer you write
Python (.py) files in a text editor and then put those files into the python interpreter to be
executed. Depending on the Editor you are using, this is either done automatically, or you
need to do it manually.

1.3 Interpreted vs. Compiled


Programming languages can be broadly classified into interpreted and compiled languages
based on how their code is executed. Interpreted languages execute code line by line using an
interpreter, allowing for easier debugging and faster development cycles. In contrast, compiled
languages require a separate compilation step, translating the entire code into machine code
before execution, which generally results in faster performance.
The following table 1.1 provides a detailed comparison between interpreted and compiled
programming languages, highlighting key differences in execution, speed, portability, develop-
ment cycle, and error handling.
CHAPTER 1. GETTING STARTED WITH PYTHON 3

Feature Interpreted Languages Compiled Languages


Execution Process Code is executed line by line at run- Code is translated into machine code
time by an interpreter. No separate before execution, generating an exe-
compilation step is required. cutable file.
Speed of Execution Slower, as translation occurs at run- Faster, as the program runs directly in
time. machine code without needing further
translation.
Portability More portable; can run on any sys- Less portable; the compiled binary is
tem with the appropriate interpreter system-specific and may require re-
installed. compilation for different platforms.
Development Cycle Faster development; changes can be Slower development cycle due to re-
tested immediately without recompi- quired compilation before testing.
lation.
Error Handling Errors are detected during runtime, Errors are detected during compila-
making debugging more flexible but tion, preventing execution until all
potentially harder. syntax errors are fixed.

Table 1.1: Comparison of Interpreted and Compiled Programming Languages

Understanding the differences between interpreted and compiled languages allows developers
to choose the right tool for their projects. Interpreted languages like Python offer simplicity and
flexibility, making them great for beginners and fast-paced development. Compiled languages
like C and C++ provide high performance and efficiency, making them ideal for complex
applications requiring speed and optimization. The choice depends on the project’s needs,
balancing factors like speed, portability, and ease of development.

1.4 Python Packages


In Python, the core language provides only the basic functionality needed to write programs,
such as handling variables, loops, conditionals, and functions. However, for more specialized
tasks, Python doesn’t include all the tools you need by default. This is where Python packages
come in.
A package in Python is essentially a collection of modules—files containing Python code—that
extend the capabilities of the language. These packages allow you to perform a wide variety
of tasks that would otherwise require you to write a lot of code yourself.
For example, if you want to:
• Work with numerical computations, you would install the NumPy package.
• Build web applications, you might use the Django or Flask package.
• Analyze data, you’d likely install pandas.
• Work with machine learning models, you could install scikit-learn or TensorFlow.
The main advantage of Python packages is that they are built and maintained by the Python
community and other developers, making it easy to add functionality to your program without
reinventing the wheel. You simply install the package using a package manager like pip and
then import it into your code.
CHAPTER 1. GETTING STARTED WITH PYTHON 4

1.5 Anaconda
Anaconda is a comprehensive open-source distribution of Python that simplifies the man-
agement and deployment of Python environments and packages. It’s specifically designed for
data science, scientific computing, and machine learning projects.
Here’s a breakdown of the key components of Anaconda:
• Python Compiler:
– Anaconda includes the Python language itself, so you don’t need to install Python
separately.
– It helps manage the Python environment and provides tools to manage packages,
libraries, and dependencies.
• Python Packages:
– Anaconda comes pre-packaged with many commonly used Python libraries for
scientific computing, such as NumPy (for numerical computing), Pandas (for
data manipulation and analysis), Matplotlib (for data visualization), SciPy, and
Scikit-learn (for machine learning).
– These packages are pre-installed and optimized to work together, saving you time
on installation and configuration.
• Spyder Editor:
– Spyder is an integrated development environment (IDE) that is also included with
Anaconda. It is designed for scientific programming and offers a user-friendly
interface with features like variable inspection, a built-in IPython console, and
debugging tools.
• Jupyter Notebook:
– Anaconda includes Jupyter Notebook, a popular web-based tool for interactive
computing. It allows you to create and share documents that contain live code,
equations, visualizations, and narrative text. This makes it a great tool for working
with data and creating reports that involve coding.
• Package Management:
– Anaconda uses its own package manager, conda, to install, update, and man-
age packages and environments. Conda makes it easier to handle dependencies,
ensuring that different versions of packages don’t conflict with each other.

1.5.1 Versions of Anaconda


• Anaconda Distribution (Free Version):
– This version is completely free and open-source. It includes the base Python
distribution along with many of the most commonly used data science libraries.
• Anaconda Enterprise (Paid Version):
– This is a paid, commercial version that adds additional features for businesses,
such as advanced security, scalability, support, and enterprise-level tools.
Web: https://www.anaconda.com
CHAPTER 1. GETTING STARTED WITH PYTHON 5

1.6 Python Editors


A Python editor is a tool for writing and editing Python code. There are three main types of
Python editors:

• Text Editors: Simple, lightweight tools with basic features like syntax highlighting.
Examples include Notepad++, Sublime Text, and Visual Studio Code.

• Integrated Development Environments (IDEs): Feature-rich environments with ad-


vanced debugging, testing, and code management tools. Popular IDEs include PyCharm,
Spyder, and Thonny.

• Online Editors: Web-based editors that require no installation. Examples include Replit
and Google Colab.

1.7 Installing Python


The Python programming language is maintained by the Python Software Foundation and is
available for download at:
https://www.python.org From this website, you can download the standard Python pack-
age, which includes:

• The Python interpreter

• A basic code editor called IDLE

For beginners, this package is sufficient for basic Python programming (see Figure 1.1).
However, for more advanced Python development, you will likely need:

• A more powerful code editor

• Additional Python packages

To get started, it is recommended to begin with the standard Python package from
python.org to learn the basics. Later, you can upgrade to a more advanced editor, manu-
ally install additional Python packages, or use Anaconda, which comes with many essential
tools pre-installed.

1.7.1 Python Windows Store App


Python 3.13 is also available in the Microsoft Store for Windows.
The Microsoft Store version of Python 3.13 provides a simplified installer for running
scripts and packages. While it is a basic version, it is sufficient for running simple scripts.
One key advantage of the Microsoft Store edition is that it receives automatic updates,
eliminating the need for manual updates.
In order to install the Microsoft Store version of Python just open Microsoft Store in
Windows and search for Python.

1.7.2 Installing Anaconda


The Spyder code editor and essential Python packages (such as NumPy, SciPy, Matplotlib,
etc.) are included in the Anaconda Distribution.
You can download and install Anaconda from: https://www.anaconda.com
CHAPTER 1. GETTING STARTED WITH PYTHON 6

1.7.3 Installing Visual Studio Code


Visual Studio Code is a simple and easy-to-use editor that supports many programming lan-
guages.
You can download and install it from:
https://code.visualstudio.com

1.8 Start using Python


1.8.1 Python IDE
The basic Python code editor is IDLE, which serves as an integrated development environment
(IDE). (See Figure 1.2.)

Figure 1.2: Python Shell/Python IDLE Editor

Other Python editors will be discussed in more detail later. For now, you can use the basic
Python IDE (IDLE) or Spyder, if you have installed the Anaconda distribution.

1.8.2 My first Python program


Let’s begin using Python by writing some simple code examples.

Example 1.8.1. Hello World Example Lets open your Python Editor and type the following:

1 print ( " Hello World " )


2

Listing 1.1: Python example

An extremely useful command is help(), which enters a help functionality to explore all
the stuff python lets you do, right from the interpreter. Press q to close the help window and
return to the Python prompt. You can use Python in different ways, either in ”interactive”
mode or in ”Script- ing” mode. The python program that you have installed will by default
act as something called an interpreter. An interpreter takes text commands and runs them as
you enter them very handy for trying things out. Yo can run Python interactively in different
ways either using the Console which is part of the operating system or the Python IDLE and
the Python Shell which is part of the basic Python installation from https://www.python.org.
CHAPTER 1. GETTING STARTED WITH PYTHON 7

1.8.3 Python Shell


In interactive mode, you use the Python Shell, as shown in Figure 1.2. Here, you enter
commands one at a time after the »> prompt in the Python Shell.
1 >>> print (" Hello , World !")

1.8.4 Running Python from the Console


A console (or ”terminal”, or ‘command prompt’) is a textual way to interact with your OS
(Operating System).
The python program that you have installed will by default act as something called an
interpreter. An interpreter takes text commands and runs them as you enter them very handy
for trying things out. Below we see how we can run Python from the Console which is part
of the OS.
Windows’ console is called the Command Prompt (cmd). An easy way to access it is by
using the key combination Windows+R (where "Windows" refers to the Windows logo key).
This will open the Run dialog. Then, type cmd and press Enter or click OK.
Alternatively, you can search for "Command Prompt" from the Start menu.
Once opened, the Command Prompt should display a prompt similar to:
1 C :\ Users \ myusername >

To enter Python’s interactive mode, simply type python and press Enter. This will launch
the Python interpreter. (See Figure ??.)

Figure 1.3: Command Prompt Windows

1.8.5 Scripting Mode


In scripting mode, Python executes pre-written scripts saved as .py files instead of running
commands interactively. This allows you to write complete programs and run them later.
Below are different ways to execute Python scripts depending on your operating system and
environment.

1.8.5.1 Run Python Scripts from the Python IDLE


In Python IDLE, you can create and run Python scripts easily.

1.8.5.1.1 Creating and Running a New Python Script in IDLE

1. Open IDLE
CHAPTER 1. GETTING STARTED WITH PYTHON 8

• Search for IDLE in the Start menu (Windows) or open it from the terminal (ma-
cOS/Linux).

2. Create a New Script

• Click File → New File, or open an existing script with File → Open....

3. Write Your Python Code


1 print ( " Hello , Python ! " )
2

4. Save the Script

• Click File → Save As... and save it with a .py extension (e.g., script.py).

5. Run the Script

• In the script window, click Run → Run Module or press F5.


• The output will appear in the Python Shell.

As shown in Figure 1.4, you can enter multiple Python commands, which together form
a complete Python program.

Figure 1.4: Python Script

To execute the script, use Run → Run Module or press F5, as shown in Figure 1.5.

Figure 1.5: Running a Python Script


CHAPTER 1. GETTING STARTED WITH PYTHON 9

1.8.5.2 Run Python Scripts from the Command Prompt in Windows


To run a Python script from the **Command Prompt** in Windows, follow these steps:

1. Open Command Prompt

• Press Win + R, type cmd, and press Enter.

2. Navigate to the Script Directory

• Use the cd command to change to the folder where your script is located:
1 cd C :\ Users \ YourUsername \ Documents \ PythonScripts
2

3. Run the Python Script

• If Python is installed and added to the system path, use:


1 python script . py
2

• If multiple versions of Python are installed, specify Python 3 explicitly:


1 python3 script . py
2

Note: Make sure you are at your system command prompt, which displays > at the end,
and not in Python mode, which has »>!
See also Figure 1.6.

Figure 1.6: Running Python Scripts from Console window

1.8.5.3 Run Python Scripts from Spyder


If you have installed the Anaconda distribution package, you can use the Spyder editor to
write and run Python scripts. See Figure 1.7.

1.8.5.3.1 Spyder Interface Overview In the Spyder editor, the interface is divided into
multiple sections:

• Script Editor (Left Panel) - This is where you write and edit your Python scripts.

• Interactive Python Shell / Console (Right Panel) - This is where you execute scripts
and see output interactively.
CHAPTER 1. GETTING STARTED WITH PYTHON 10

1.8.5.3.2 Running a Python Script in Spyder To execute a Python script in Spyder,


follow these steps:

1. Open Spyder

• Launch Spyder from the Anaconda Navigator or by running spyder in the com-
mand prompt.

2. Create or Open a Python Script

• Click File → New File to create a new script.


• Alternatively, open an existing script using File → Open....

3. Write Python Code


1 print ( " Hello from Spyder ! " )
2

4. Save the Script

• Click File → Save As... and save the script with a .py extension.

5. Run the Script

• Click the green Run button or press F5.


• The output will be displayed in the Console on the right side.

See Figure 1.7 for an illustration of the Spyder interface.

Figure 1.7: Running a Python Script in Spyder


Chapter 2

Basic Python Programming

2.1 Basic Python Program


We will start using Python and create some code examples. We use the basic IDLE editor (or
another Python Editor)

Example 2.1.1. Hello World Example Lets open your Python Editor and type the following:

1 print ( " Hello World " )


2

Listing 2.1: Python example

2.1.1 Get Help


An extremely useful command is help(), which enters a help functionality to explore all the
stuff python lets you do, right from the interpreter. Press q to close the help window and
return to the Python prompt.

2.2 Variables
Variables are defined with the assignment operator, “=”. Python is dynamically typed, mean-
ing that variables can be assigned without declaring their type, and that their type can change.
Values can come from constants, from computation involving values of other variables, or from
the output of a function.

Example 2.2.1. Creating and using Variables in Python

We use the basic IDLE (or another Python Editor) and type the following:
1 >>> x = 3
2 >>> x
3 3
Listing 2.2: Using Variables in Python

Here we define a variable and sets the value equal to 3 and then print the result to the
screen.
You can write one command by time in the IDLE. If you quit IDLE the variables and data
are lost. Therefore, if you want to write a somewhat longer program, you are better off using
a text editor to prepare the input for the interpreter and running it with that file as input

11
CHAPTER 2. BASIC PYTHON PROGRAMMING 12

instead. This is known as creating a script. Python scripts or programs are save as a text file
with the extension .py
Example 2.2.2. Calculations in Python We can use variables in a calculation like this:
1 x = 3
2 y = 3 * x
3 print ( y )
Listing 2.3: Using and Printing Variables in Python
We can implementing the formula y = ax+b like this:
1 a = 2
2 b = 5
3 x = 3
4 y = a*x + b
5 print ( y )
Listing 2.4: Calculations in Python

As seen in the examples, you can use the print() command in order to show the values on
the screen.
A variable can have a short name (like x and y) or a more descriptive name (sum, amount,
etc).
You don’t need to define the variables before you use them (like you need to do in, e.g.,
C/C++).
Here are some basic rules for Python variables:

• A variable name must start with a letter or the underscore (_) character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters (A-z, 0-9) and under-
scores(_)
• Variable names are case-sensitive, e.g., amount, Amount and AMOUNT are three differ-
ent variables.

2.2.1 Numbers
There are three numeric types in Python:
• int
• float
• complex
in Python, numeric variables are automatically created when you assign a value to them. You
don’t need to explicitly declare a variable type like in some other languages (e.g., Java or
C++).
1 x = 10 # Integer
2 y = 3.14 # Float
3 z = 2 + 3 j # Complex number
4 print ( type ( x ) ) # < class ’ int ’>
5 print ( type ( y ) ) # < class ’ float ’>
6 print ( type ( z ) ) # < class ’ complex ’>
Listing 2.5: Numeric Types in Python
CHAPTER 2. BASIC PYTHON PROGRAMMING 13

• Python dynamically assigns types based on the assigned value.


• You don’t need int x = 10; like in statically typed languages.
• You can check the type using type(variable).
• Python supports integers (int), floating-point numbers (float), and complex numbers
(complex).

2.2.2 Strings
In Python, strings can be enclosed in either single (’) or double (") quotation marks, and both
are treated the same.
1 # Both are valid strings
2 string1 = ’ Hello ’
3 string2 = " Hello "
4 print ( type ( string1 ) ) # < class ’ str ’>
5 print ( string1 ) # Output : Hello
6 print ( string2 ) # Output : Hello
Listing 2.6: Strings in Python
In Python, strings are sequences of characters, meaning they can be treated like arrays.
This allows us to manipulate them using built-in functions and indexing.
Example 2.2.3. String Indexing Built-in Functions Below we see examples of using strings
in Python:
1 text = " Python "
2
3 # Indexing ( zero - based ) : indexing allows you to access individual
characters in a string using their position ( index )
4 print ( text [0]) # Output : P
5 print ( text [3]) # Output : h
6
7 # Negative Indexing ( counting from the end )
8
9 print ( text [ -1]) # Output : n
10 print ( text [ -2]) # Output : o
11
12 # Slicing ( getting a substring )
13 print ( text [0:4]) # Output : Pyth ( from index 0 to 3)
14 print ( text [:2]) # Output : Py ( from start to index 1)
15 print ( text [2:]) # Output : thon ( from index 2 to end )
16
17 # Some Built - in String Functions
18 print ( len ( text ) ) # Output : 6 ( length of string )
19 print ( text . upper () ) # Output : PYTHON ( convert to uppercase )
20 print ( text . lower () ) # Output : python ( convert to lowercase )
21 print ( text . replace ( " P " , " J " ) ) # Output : Jython ( replace ’P ’ with ’J ’)
22
23 # Checking for substrings
24 print ( " th " in text ) # Output : True ( checks if ’ th ’ exists in the string )
25 print ( " z " not in text ) # Output : True ( checks if ’z ’ is NOT in the string
)
Listing 2.7: Strings in Python
As you see in the example, there are many built-in functions form manipulating strings in
Python. The Example shows only a few of them. Strings in Python are arrays of bytes, and
we can use index to get a specific character within the string as shown in the example code.
CHAPTER 2. BASIC PYTHON PROGRAMMING 14

2.2.3 String Input


In Python, you can take command-line input from the user using the input() function. This
allows interaction by asking users for input and processing their responses.

Example 2.2.4. Basic User Input

1 name = input ( " Enter your name : " )


2 print ( " Hello , " + name + " ! " ) # can only concatenate str ( not " int ") to str
3 print ( " Hello " , name , " ! " )
Listing 2.8: Basic User Input

Example 2.2.5. Taking Numeric Input

By default, input() returns a string. To handle numbers, convert the input using
int() or float() :
1 age = int ( input ( " Enter your age : " ) )
2 print ( " You are " , age , " years old . " )
Listing 2.9: Numeric Input

In Python, It is possible to get multiple values from the user in one line. We can accept
two or three values from the user.

Example 2.2.6. For example, in a single execution of the input() function, we can ask the
user his/her name, age, and phone number and store it in three different variables.
Let’s see how to do this.

• Take each input separated by space

• Split input string using split() get the value of individual input

1 name , age , phone_number = input ( " Enter your Name , Age , phone number
separated by space " ) . split ()
2 print ( " \ n " )
3 print ( " User Details : " , name , age , phone_number )
Listing 2.10: Get Multiple inputs From a User in One Line

Important Notes: The input values will be strings by default. If you need age as number,
convert it explicitly
1 name , age , phone_number = input ( " Enter your Name , Age , phone number
separated by space " ) . split ()
2 age = int ( age ) # Convert age to integer
3 print ( " \ n User Details : " )
4 print ( " Name : " , name )
5 print ( " Age : " , age )
6 print ( " Phone number : " , phone_number )
Listing 2.11: Get Multiple inputs From a User in One Line
CHAPTER 2. BASIC PYTHON PROGRAMMING 15

2.3 Built-in Functions


Python has many built-in functions that help with various tasks like printing, mathematical
operations, and data manipulation.
1 print ( " Hello , World ! " ) # Output text to the console
2
3 x = len ( " Python " ) # Get the length of a string
4 print ( x ) # Output : 6
5
6 y = max (10 , 20 , 30) # Find the maximum value
7 print ( y ) # Output : 30
8
9 z = round (3.14159 , 2) # Round a number to 2 decimal places
10 print ( z ) # Output : 3.14
Listing 2.12: Numeric Input

2.4 Python Standard Library


The Python Standard Library is a collection of built-in modules that provide various function-
alities without needing separate installation.

2.4.1 Importing Modules in Different Ways


There are several ways to import and use functions from a module, each with its advantages
and disadvantages.

2.4.1.1 Importing a Specific Function (Recommended for Memory Efficiency)


If you only need a single function from a module, import just that function.
1 from math import sin
2
3 print ( sin (3.14) ) # Output : 0.0 01592 6529 1648 68282
Listing 2.13: Importing a Specific Function

2.4.1.2 Importing Multiple Specific Functions


You can import multiple functions at once.
1 from math import sin , cos , log
2
3 print ( sin (0) ) # Output : 0.0
4 print ( cos (0) ) # Output : 1.0
5 print ( log (10) ) # Output : 2.302585092994046
Listing 2.14: Importing Multiple Specific Functions

2.4.1.3 Importing the Entire Module


If you need many functions, import the full module.
CHAPTER 2. BASIC PYTHON PROGRAMMING 16

1 import math
2
3 print ( math . sin (3.14) )
4 print ( math . cos (0) )
5 print ( math . log (10) )
6 print ( math . pi ) # Accessing a constant
Listing 2.15: Importing the Entire Module

2.4.1.4 Using an Alias for a Module (Shorter Code)


To simplify calls, you can use an alias (nickname) for the module.
1 import math as m
2
3 print ( m . sin (3.14) )
4 print ( m . cos (0) )
5 print ( m . pi )
Listing 2.16: Using an Alias for a Module

2.4.1.5 Importing Everything (*) from a Module (Not Recommended)

1 from math import *


2 print ( sin (3.14) )
3 print ( log (10) )
Listing 2.17: Importing Everything (*) from a Module

2.5 Using Python Libraries, Packages, and Modules


Python is designed to be highly extensible, meaning that not all functionality is built into its
core. Instead, Python allows the use of external libraries and modules to extend its capabilities.

2.5.1 Advantages and Disadvantages


Advantages:

• Keeps Python lightweight and flexible.

• Provides specialized tools for scientific computing, data visualization, and more.

Disadvantages:

• Some packages need to be installed separately before use.

• Importing multiple libraries may lead to function name conflicts.

2.5.2 Important Python Libraries:


• NumPy is the fundamental package for scientific computing in Python. It provides
support for Multi-dimensional arrays and matrices, Mathematical functions for array
operations, Linear algebra, Fourier transforms, and random number generation.
CHAPTER 2. BASIC PYTHON PROGRAMMING 17

• SciPy is an open-source Python library used for scientific and technical computing. It
includes modules for: Optimization and linear algebra, Integration and interpolation,
Signal and image processing and Differential equation solvers.

• Matplotlib is a Python 2D plotting library used to create static, animated, and inter-
active visualizations. It is commonly used for Line plots, bar charts, and histograms,
Scatter plots and 3D visualizations qnd Customizable figures for publication-quality
graphics.

Using Libraries

Example 2.5.1. Using the NumPy library for mathematical functions:

1 import numpy as np
2 x = 3
3 y = np . sin ( x )
4 print ( y )
Listing 2.18: Using the NumPy library

Example 2.5.2. Using both the math module (from Python’s Standard Library) and the
NumPy library:

1 import math as mt
2 import numpy as np
3 x = 3
4 # Using the math module
5 y1 = mt . sin ( x )
6 print ( y1 )
7 # Using the NumPy library
8 y2 = np . sin ( x )
9 print ( y2 )
Listing 2.19: Using both the math module and the NumPy library

In this example, both math.sin() and numpy.sin() compute the sine of x, but they
belong to different libraries.
Important Note! In the previous example, we used the sin() function, which exists in
both the math module (from Python’s Standard Library) and the NumPy library. In this case,
both functions return the same result.
However, the following approach is not recommended:
1 from math import *
2 from numpy import *
3 x = 3
4 y = sin ( x )
5 print ( y )
6
7 y = sin ( x )
8 print ( y )
Listing 2.20: Importing everything using from module import *

Why is this problematic? Importing everything using from module import * can lead
to confusion if multiple libraries have functions with the same name. If two different libraries
define sin(), Python will not know which one to use, leading to unexpected behavior.
Better Approach To avoid conflicts, always use module prefixes or aliases:
CHAPTER 2. BASIC PYTHON PROGRAMMING 18

1 import math as mt
2 import numpy as np
3
4 x = 3
5 y1 = mt . sin ( x )
6 print ( y1 )
7
8 y2 = np . sin ( x )
9 print ( y2 )
Listing 2.21: Use module prefixes or aliases

This makes the code clear and prevents accidental function name conflicts.

2.5.3 Plotting in Python


In Python, you often need to create plots or charts to visualize data. To do this, an external
library is required. The most commonly used library for plotting is Matplotlib.
Common Matplotlib Functions
Matplotlib provides several useful functions for plotting, including:

• plot() – Creates a line plot.

• title() – Adds a title to the plot.

• xlabel() – Labels the x-axis.

• ylabel() – Labels the y-axis.

• axis() – Sets axis limits.

• grid() – Adds a grid to the plot.

• subplot() – Creates multiple subplots in one figure.

• legend() – Adds a legend to the plot.

• show() – Displays the plot.

Example 2.5.3. Here is a simple example using Matplotlib:

1 import matplotlib . pyplot as plt


2
3 x = [1 , 2 , 3 , 4 , 5]
4 y = [10 , 15 , 7 , 12 , 9]
5
6 plt . plot (x , y , marker = ’o ’ , linestyle = ’ - ’)
7 plt . title ( " Basic Line Plot " )
8 plt . xlabel ( "X - axis " )
9 plt . ylabel ( "Y - axis " )
10 plt . grid ( True )
11 plt . show ()
Listing 2.22: Basic Plotting
CHAPTER 2. BASIC PYTHON PROGRAMMING 19

Figure 2.1: Plotting in Python


Chapter 3

Python Programming

We have been through the basics in Python, such as variables, using some basic built-in
functions, basic plotting, etc. You may come far only using these things, but to create real
applications in Python, you need to use control structures like if-else statements, loops, and
arrays (lists, tuples, etc.).
If you are familiar with one or more other programming language, these features should
be familiar and known to you. All programming languages has these features built-in, but the
syntax is slightly different from one language to another.

3.1 Conditional Expressions


Python provides various operators for comparing values. The result of a comparison is a
boolean value, either True or False.

• == equal to

• != not equal to

• < less than

• > greater than

• <= less than or equal to

• >= greater than or equal to

Lets open your Python Editor and type the following:


1 >>> 2 < 3
2 True
3 >>> 2 > 3
4 False
Listing 3.1: operators for comparing
It is even possible to combine these operators.
1 >>> x = 5
2 >>> 2 < x < 10
3 True
4 >>> 2 < 3 < 4 < 5 < 6
5 True
Listing 3.2: combine operators example

20
CHAPTER 3. PYTHON PROGRAMMING 21

Conditional operators also work on strings, with comparisons based on lexical order.
1
2 >>>" apple " < " banana " # True ( ’ a ’ comes before ’b ’ alphabetically )
3 True
4 >>>" hello " > " world " # False ( ’ h ’ comes before ’w ’ ( so it ’s smaller ) )
5 False
6 >>>" Python " == " python " # False ( case - sensitive : uppercase and lowercase
letters have different Unicode values .)
7 False
8 " cat " != " dog " # True since the words are different
9 True
Listing 3.3: Comparing Strings

There are few logical operators to combine boolean values.

• a and b is True only if both a and b are True.

• a or b is True if either a or b is True.

• not a is True only if a is False.

1 >>> True and True


2 True
3 >>> True and False
4 False
5 >>> 2 < 3 and 5 < 4
6 False
7 >>> 2 < 3 or 5 < 4
8 True
Listing 3.4: Examples of Logical Operators

3.1.1 If statement
In control statements, The if statement is the simplest form. It takes a condition and evaluates
to either True or False.
Syntax of the if statement
1 if condition :
2 statement 1
3 statement 2
4 statement n
Listing 3.5: Syntax of the if statement

Let’s look at an example of the if statement. In this example, we will check whether a
number is greater than 5.
1 x = 10
2 if x > 5:
3 print ( " x is greater than 5 " )
4 print ( " Next lines of code " )
Listing 3.6: Basic If Statement

If the condition x > 5 is True, the indented code runs.


CHAPTER 3. PYTHON PROGRAMMING 22

3.1.2 If–else statement


The if-else statement checks the condition and executes the if block of code when the condition
is True, and if the condition is False, it will execute the else block of code.
Syntax of the if-else statement
1 if condition :
2 statement 1
3 else :
4 statement 2
Listing 3.7: Syntax of the if-else statement

If the condition is True, then statement 1 will be executed If the condition is False,
statement 2 will be executed.
1 x = 3
2 if x > 5:
3 print ( " x is greater than 5 " )
4 else :
5 print ( " x is 5 or less " )
Listing 3.8: If-Else Statement

The else block runs if the if condition is False.


1 password = input ( ’ Enter password ’)
2
3 if password == " Python2025 " :
4 print ( " Correct password " )
5 else :
6 print ( " Incorrect Password " )
Listing 3.9: Exemple If-Else Statement

3.1.3 Chain multiple if statement


In Python, the if-elif-else condition statement has an elif blocks to chain multiple conditions
one after another. This is useful when you need to check multiple conditions.
Syntax of the if-elif-else statement:
1 if condition -1:
2 statement 1
3 elif condition -2:
4 stetement 2
5 elif condition -3:
6 stetement 3
7 ...
8 else :
9 statement
Listing 3.10: Syntax of the if-elif-else statement

1 x = 5
2 if x > 5:
3 print ( " x is greater than 5 " )
4 elif x == 5:
5 print ( " x is exactly 5 " )
6 else :
7 print ( " x is less than 5 " )
Listing 3.11: If-Elif-Else (Multiple Conditions)
CHAPTER 3. PYTHON PROGRAMMING 23

elif is used for additional conditions. Only one block runs, based on the first True
condition.

3.1.4 Nested if-else statement


In Python, the nested if-else statement is an if statement inside another if-else statement. It
is allowed in Python to put any number of if statements in another if statement. Indentation
is the only way to differentiate the level of nesting. The nested if-else is useful when we want
to make a series of decisions.
Syntax of the nested-if-else:
1 if conditon_outer :
2 if condition_inner :
3 statement of inner if
4 else :
5 statement of inner else :
6 statement of outer if
7 else :
8 Outer else
9 statement outside if block
Listing 3.12: Nested if-else statemen

Example 3.1.1. Find a greater number between two numbers


1 num1 = int ( input ( ’ Enter first number ’) )
2 num2 = int ( input ( ’ Enter second number ’) )
3
4 if num1 >= num2 :
5 if num1 == num2 :
6 print ( num1 , ’ and ’ , num2 , ’ are equal ’)
7 else :
8 print ( num1 , ’ is greater than ’ , num2 )
9 else :
10 print ( num1 , ’ is smaller than ’ , num2 )
Listing 3.13: Find a greater number between two numbers

3.1.5 Using Logical Operators(and, or, not) in If Statements


1 x = 10
2 y = 20
3 if x > 5 and y > 15:
4 print ( " Both conditions are True " ) # This runs because both conditions
are True
5 if x > 5 or y < 15:
6 print ( " At least one condition is True " ) # This runs because x > 5 is
True
7 if not x < 5:
8 print ( " x is NOT less than 5 " ) # This runs because x < 5 is False , and
‘not ‘ makes it True
Listing 3.14: Using Logical Operators (and

• and requires both conditions to be True.


• or requires at least one condition to be True.
• not reverses the condition.
CHAPTER 3. PYTHON PROGRAMMING 24

3.2 Python Lists


In Python, arrays are usually represented using lists since Python does not have a built-in
array type like other programming languages (e.g., Java or C).

Figure 3.1: Python List

3.2.1 Creating a Python list


The list can be created using either the list constructor or using square brackets [] .

• Using list() constructor: In general, the constructor of a class has its class name.
Similarly, Create a list by passing the comma-separated values inside the list().

• Using square bracket ( [] ): In this method, we can create a list simply by enclosing
the items inside the square brackets.

1
2 # Using list constructor
3 my_list1 = list ((1 , 2 , 3) )
4 print ( my_list1 )
5 # Output [1 , 2 , 3]
6
7 # Using square brackets []
8 my_list2 = [1 , 2 , 3]
9 print ( my_list2 )
10 # Output [1 , 2 , 3]
11
12 # with heterogeneous items
13 my_list3 = [1.0 , ’ Rym ’ , 3]
14 print ( my_list3 )
15 # Output [1.0 , ’ Rym ’, 3]
16
17 # empty list using list ()
18 my_list4 = list ()
19 print ( my_list4 )
20 # Output []
21
22 # empty list using []
23 my_list5 = []
24 print ( my_list4 )
CHAPTER 3. PYTHON PROGRAMMING 25

25 # Output []
Listing 3.15: Creating a List

3.2.2 Length of a List


In order to find the number of items present in a list, we can use the len() function
1 my_list = [1 , 2 , 3]
2 print ( len ( my_list ) )
3 # output 3
Listing 3.16: Length of a List

3.2.3 Accessing items of a List


The items in a list can be accessed through indexing and slicing. This section will guide you
by accessing the list using the following two ways

• Using indexing, we can access any item from a list using its index number

• Using slicing, we can access a range of items from a list

3.2.3.1 Indexing
The list elements can be accessed using the “indexing” technique. Lists are ordered collections
with unique indexes for each item. We can access the items in the list using this index number.

Figure 3.2: Python Positive and Negative indexing

To access the elements in the list from left to right, the index value starts from zero to
(length of the list-1) can be used. For example, if we want to access the 3rd element we
need to use 2 since the index value starts from 0.
1 my_list = [10 , 20 , ’ Samy ’ , 12.50 , ’ Rym ’]
2 # accessing 2 nd element of the list
3 print ( my_list [1]) # 20
4 # accessing 5 th element of the list
5 print ( my_list [4]) # ’ Rym ’
Listing 3.17: Accessing Elements Positive indexing

As seen in the above example we accessed the second element in the list by passing the
index value as 1. Similarly, we passed index 4 to access the 5th element in the list.
CHAPTER 3. PYTHON PROGRAMMING 26

Negative Indexing The elements in the list can be accessed from right to left by using
negative indexing. The negative value starts from (-1) to (-length of the list). It indicates
that the list is indexed from the reverse/backward.
1 my_list = [10 , 20 , ’ Samy ’ , 12.50 , ’ Rym ’]
2 # accessing last element of the list
3 print ( my_list [ -1]) # output ’ Rym ’
4
5 # accessing second last element of the list
6 print ( my_list [ -2]) # output 12.5
7
8 # accessing 4 th element from last
9 print ( my_list [ -4]) # output 20
Listing 3.18: Accessing Elements Negative indexing

As seen in the above example to access the 4th element from the last (right to left) we pass
‘-4’ in the index value.

3.2.3.2 List Slicing


Slicing a list implies, accessing a range of elements in a list. For example, if we want to get
the elements in the position from 3 to 7, we can use the slicing method. We can even modify
the values in a range by using this slicing technique.
The below is the syntax for list slicing.
1 listname [ start_index : end_index : step ]
Listing 3.19: the syntax for list slicing

• The start_index denotes the index position from where the slicing should begin and
the end_index parameter denotes the index positions till which the slicing should be
done.

• The step allows you to take each nth-element within start_index:end_index range.

Example 3.2.1.

1 my_list = [10 , 20 , ’ Samy ’ , 12.50 , ’ Rym ’ , 25 , 50]


2 # Extracting a portion of the list from 2 nd till 5 th element
3 print ( my_list [2:5]) # Output [ ’ Samy ’, 12.5 , ’ Rym ’]
Listing 3.20: list slicing

Let us see few more examples of slicing a list such as:

• Extract a portion of the list

• Reverse a list

• Slicing with a step

• Slice without specifying start or end position


CHAPTER 3. PYTHON PROGRAMMING 27

1 my_list = [5 , 8 , ’ Samy ’ , 7.50 , ’ Rym ’]


2
3 # slice first four items
4 print ( my_list [:4]) # Output [5 , 8 , ’ Samy ’, 7.5]
5
6 # print every second element
7 # with a skip count 2
8 print ( my_list [::2]) # Output [5 , ’ Samy ’, ’ Rym ’]
9
10 # reversing the list
11 print ( my_list [:: -1]) # Output [ ’ Rym ’, 7.5 , ’ Samy ’, 8 , 5]
12
13
14 # Without end_value
15 # Stating from 3 nd item to last item
16 print ( my_list [3:]) # Output [7.5 , ’ Rym ’]
Listing 3.21: more examples of slicing a list

3.2.4 Iterating a List


The objects in the list can be iterated over one by one, by using a for a loop.
1 my_list = [5 , 8 , ’ Samy ’ , 7.50 , ’ Rym ’]
2
3 # iterate a list
4 for item in my_list :
5 print ( item )
Listing 3.22: Iterating a List by using a for a loop

3.2.4.1 Iterate along with an index number


The index value starts from 0 to (length of the list-1). Hence using the function range()is
ideal for this scenario.
The range function returns a sequence of numbers. By default, it returns starting from
0 to the specified number (increments by 1). The starting and ending values can be passed
according to our needs.

Example 3.2.2.

1 my_list = [5 , 8 , ’ Samy ’ , 7.50 , ’ Rym ’]


2
3 # iterate a list
4 for i in range (0 , len ( my_list ) ) :
5 # print each item using index number
6 print ( my_list [ i ])
Listing 3.23: Iterating a List by using the function range()

3.2.5 Adding elements to the list


We can add a new element/list of elements to the list using the list methods such as append() ,
insert() , and extend() .
CHAPTER 3. PYTHON PROGRAMMING 28

3.2.5.1 Append item at the end of the list


The append() method will accept only one parameter and add it at the end of the list.
Let’s see the example to add the element ‘Rym’ at the end of the list.
1 my_list = list ([5 , 8 , ’ Samy ’ , 7.50])
2
3 # Using append ()
4 my_list . append ( ’ Rym ’)
5 print ( my_list ) # Output [5 , 8 , ’ Samy ’, 7.5 , ’ Rym ’]
6
7 # append the nested list at the end
8 my_list . append ([25 , 50 , 75])
9 print ( my_list ) # Output [5 , 8 , ’ Samy ’, 7.5 , ’ Rym ’, [25 , 50 , 75]]
Listing 3.24: Append item at the end of the list

3.2.5.2 Add item at the specified position in the list


Use the insert() method to add the object/item at the specified position in the list. The
insert method accepts two parameters position and object.
1 insert ( index , object )
Listing 3.25: the syntax for the insert method

It will insert the object in the specified index. Let us see this with an example.
1 my_list = list ([5 , 8 , ’ Samy ’ , 7.50])
2
3 # Using insert ()
4 # insert 25 at position 2
5 my_list . insert (2 , 25)
6 print ( my_list ) # Output [5 , 8 , 25 , ’ Samy ’, 7.5]
7
8 # insert nested list at position 3
9 my_list . insert (3 , [25 , 50 , 75])
10 print ( my_list ) # Output [5 , 8 , 25 , [25 , 50 , 75] , ’ Samy ’, 7.5]
Listing 3.26: Modifying Elements

As seen in the above example item 25 is added at the index position 2.

3.2.5.3 Using extend()


The extend method will accept the list of elements and add them at the end of the list. We
can even add another list by using this method.
Let’s add three items at the end of the list.
1 my_list = list ([5 , 8 , ’ Samy ’ , 7.50])
2
3 # Using extend ()
4 my_list . extend ([25 , 75 , 100])
5 print ( my_list ) # Output [5 , 8 , ’ Samy ’, 7.5 , 25 , 75 , 100]
Listing 3.27: Using extend()

As seen in the above example we have three integer values at once. All the values get
added in the order they were passed and it gets appended at the end of the list.
CHAPTER 3. PYTHON PROGRAMMING 29

3.2.6 Modify the items of a List


The list is a mutable sequence of iterable objects. It means we can modify the items of a list.
Use the index number and assignment operator (=) to assign a new value to an item.
Let’s see how to perform the following two modification scenarios

• Modify the individual item.

• Modify the range of items

1 my_list = list ([2 , 4 , 6 , 8 , 10 , 12])


2
3 # modify single item
4 my_list [0] = 20
5 print ( my_list )
6 # Output [20 , 4 , 6 , 8 , 10 , 12]
7
8 # modify range of items
9 # modify from 1 st index to 4 th
10 my_list [1:4] = [40 , 60 , 80]
11 print ( my_list )
12 # Output [20 , 40 , 60 , 80 , 10 , 12]
13
14 # modify from 3 rd index to end
15 my_list [3:] = [80 , 100 , 120]
16 print ( my_list )
17 # Output [20 , 40 , 60 , 80 , 100 , 120]
Listing 3.28: Modify the items of a List

3.2.7 Modify all items


Use for loop to iterate and modify all items at once. Let’s see how to modify each item of a
list.
1 my_list = list ([2 , 4 , 6 , 8])
2
3 # change value of all items
4 for i in range ( len ( my_list ) ) :
5 # calculate square of each number
6 square = my_list [ i ] * my_list [ i ]
7 my_list [ i ] = square
8
9 print ( my_list )
10 # Output [4 , 16 , 36 , 64]
Listing 3.29: Modify all items

3.2.8 Removing elements from a List


The elements from the list can be removed using the following list methods.

3.2.8.1 Remove specific item


Use the remove() method to remove the first occurrence of the item from the list.
Note: It Throws a keyerror if an item not present in the original list.

Example 3.2.3.
CHAPTER 3. PYTHON PROGRAMMING 30

Method Description
remove(item) To remove the first occurrence of the item from the list.
pop(index) Removes and returns the item at the given index from the list.
clear() To remove all items from the list. The output will be an empty
list.
del list_name Delete the entire list.

Table 3.1: Python List methods to remove item

1 my_list = list ([2 , 4 , 6 , 8 , 10 , 12])


2
3 # remove item 6
4 my_list . remove (6)
5 # remove item 8
6 my_list . remove (8)
7
8 print ( my_list )
9 # Output [2 , 4 , 10 , 12]
Listing 3.30: Remove specific item

3.2.8.2 Remove all occurrence of a specific item


Use a loop to remove all occurrence of a specific item
1 my_list = list ([6 , 4 , 6 , 6 , 8 , 12])
2
3 for item in my_list :
4 my_list . remove (6)
5
6 print ( my_list )
7 # Output [4 , 8 , 12]
Listing 3.31: Remove all occurrence of a specific item

3.2.8.3 Remove item present at given index


Use the pop() method to remove the item at the given index. The pop() method removes
and returns the item present at the given index.
Note: It will remove the last time from the list if the index number is not passed.
Example 3.2.4.

1 my_list = list ([2 , 4 , 6 , 8 , 10 , 12])


2
3 # remove item present at index 2
4 my_list . pop (2)
5 print ( my_list )
6 # Output [2 , 4 , 8 , 10 , 12]
7
8 # remove item without passing index number
9 my_list . pop ()
10 print ( my_list )
11 # Output [2 , 4 , 8 , 10]
Listing 3.32: Remove item present at given index
CHAPTER 3. PYTHON PROGRAMMING 31

3.2.8.4 Remove the range of items


Use del keyword along with list slicing to remove the range of items
1 my_list = list ([2 , 4 , 6 , 8 , 10 , 12])
2
3 # remove range of items
4 # remove item from index 2 to 5
5 del my_list [2:5]
6 print ( my_list )
7 # Output [2 , 4 , 12]
8
9 # remove all items starting from index 3
10 my_list = list ([2 , 4 , 6 , 8 , 10 , 12])
11 del my_list [3:]
12 print ( my_list )
13 # Output [2 , 4 , 6]
Listing 3.33: Remove the range of items

3.2.8.5 Remove all items


Use the list’ clear() method to remove all items from the list. The clear() method truncates
the list.
1 my_list = list ([2 , 4 , 6 , 8 , 10 , 12])
2
3 # clear list
4 my_list . clear ()
5 print ( my_list )
6 # Output []
7
8 # Delete entire list
9 del my_list
Listing 3.34: Adding and Removing Elements

3.2.9 Finding an element in the list


Use the index() function to find an item in a list.
The index() function will accept the value of the element as a parameter and returns the
first occurrence of the element or returns ValueError if the element does not exist.
1 my_list = list ([2 , 4 , 6 , 8 , 10 , 12])
2
3 print ( my_list . index (8) )
4 # Output 3
5
6 # returns error since the element does not exist in the list .
7 # my_list . index (100)
Listing 3.35: Finding an element in the list

3.2.10 Concatenation of two lists


The concatenation of two lists means merging of two lists. There are two ways to do that.

• Using the + operator.


CHAPTER 3. PYTHON PROGRAMMING 32

• Using the extend() method. The extend() method appends the new list’s items at
the end of the calling list.

Example 3.2.5.

1 my_list1 = [1 , 2 , 3]
2 my_list2 = [4 , 5 , 6]
3
4 # Using + operator
5 my_list3 = my_list1 + my_list2
6 print ( my_list3 )
7 # Output [1 , 2 , 3 , 4 , 5 , 6]
8
9 # Using extend () method
10 my_list1 . extend ( my_list2 )
11 print ( my_list1 )
12 # Output [1 , 2 , 3 , 4 , 5 , 6]
Listing 3.36: Concatenation of two lists

3.2.11 Copying a list


There are two ways by which a copy of a list can be created. Let us see each one with an
example.

3.2.11.1 Using assignment operator (=)


This is a straightforward way of creating a copy. In this method, the new list will be a deep
copy. The changes that we make in the original list will be reflected in the new list.
This is called deep copying.
1 my_list1 = [1 , 2 , 3]
2
3 # Using = operator
4 new_list = my_list1
5 # printing the new list
6 print ( new_list )
7 # Output [1 , 2 , 3]
8
9 # making changes in the original list
10 my_list1 . append (4)
11
12 # print both copies
13 print ( my_list1 )
14 # result [1 , 2 , 3 , 4]
15 print ( new_list )
16 # result [1 , 2 , 3 , 4]
Listing 3.37: deep copying

As seen in the above example a copy of the list has been created. The changes made to
the original list are reflected in the copied list as well.

3.2.11.2 Using the copy() method


The copy method can be used to create a copy of a list. This will create a new list and any
changes made in the original list will not reflect in the new list. This is shallow copying
CHAPTER 3. PYTHON PROGRAMMING 33

1 my_list1 = [1 , 2 , 3]
2
3 # Using copy () method
4 new_list = my_list1 . copy ()
5 # printing the new list
6 print ( new_list )
7 # Output [1 , 2 , 3]
8
9 # making changes in the original list
10 my_list1 . append (4)
11
12 # print both copies
13 print ( my_list1 )
14 # result [1 , 2 , 3 , 4]
15 print ( new_list )
16 # result [1 , 2 , 3]
Listing 3.38: shallow copying

As seen in the above example a copy of the list has been created. The changes made to
the original list are not reflected in the copy.

3.2.12 List operations


We can perform some operations over the list by using certain functions like sort() ,
reverse() , clear() etc.

3.2.12.1 Sort List using sort()


The sort function sorts the elements in the list in ascending order.
1 mylist = [3 ,2 ,1]
2 mylist . sort ()
3 print ( mylist )
Listing 3.39: Using sort()

As seen in the above example the items are sorted in the ascending order.

3.2.12.2 Reverse a List using reverse()


The reverse function is used to reverse the elements in the list.
1 mylist = [3 , 4 , 5 , 6 , 1]
2 mylist . reverse ()
3 print ( mylist )
Listing 3.40: Using reverse()

3.2.13 Python Built-in functions with List


In addition to the built-in methods available in the list, we can use the built-in functions as
well on the list. Let us see a few of them for example.

3.2.13.1 Using max() & min()


The max function returns the maximum value in the list while the min function returns the
minimum value in the list.
CHAPTER 3. PYTHON PROGRAMMING 34

1 mylist = [3 , 4 , 5 , 6 , 1]
2 print ( max ( mylist ) ) # returns the maximum number in the list .
3 print ( min ( mylist ) ) # returns the minimum number in the list .
Listing 3.41: Using max() min()
As seen in the above example the max function returns 6 and min function returns 1.

3.2.13.2 Using sum()


The sum function returns the sum of all the elements in the list.
1 mylist = [3 , 4 , 5 , 6 , 1]
2 print ( sum ( mylist ) )
Listing 3.42: Using sum()

3.2.13.3 Using enumerate()


The enumerate() function allows obtaining both index and value simultaneously, without
using range(len()) .
Example 3.2.6. Using enumerate()

1 numbers = [10 , 20 , 30 , 40]


2
3 for index , value in enumerate ( numbers ) :
4 print ( f " Index { index }: { value } " )
Listing 3.43: Using enumerate()

enumerate() is more readable and efficient than range(len()) .

3.3 Creating Tuples


A tuple is an immutable collection (its elements cannot be changed after creation).
Example 3.3.1. Defining a Tuple

1 my_tuple = (10 , 20 , 30)


2 print ( my_tuple ) # Output : (10 , 20 , 30)
Listing 3.44: Creating Tuples

Example 3.3.2. Accessing Tuple Elements

1 print ( my_tuple [0]) # Output : 10


2 print ( my_tuple [ -1]) # Output : 30
Listing 3.45: Accessing Tuple Elements

Example 3.3.3. Converting a List to a Tuple

1
2 my_list = [1 , 2 , 3 , 4]
3 my_tuple = tuple ( my_list )
4 print ( my_tuple ) # Output : (1 , 2 , 3 , 4)
Listing 3.46: Converting a List to a Tuple
Tuples are faster and use less memory than lists.
CHAPTER 3. PYTHON PROGRAMMING 35

3.4 For Loops


Using for loop, we can iterate any sequence or iterable variable. The sequence can be string,
list, dictionary, set, or tuple.
Syntax of for loop:
1 for element in sequence :
2 body of for loop
Listing 3.47: Syntax of for loop

Example 3.4.1. Using range() in a For Loop The range() function generates a sequence of
numbers.

1 for i in range (5) : # The loop executes 5 times ( from 0 to 4) .


2 print ( i )
Listing 3.48: Using range()

Example 3.4.2. To start from a specific number:

1 for i in range (2 , 6) : # The first value (2) is included , but the last (6)
is excluded .
2 print ( i )
Listing 3.49: To start from a specific number

Example 3.4.3. To specify a step:

1 for i in range (1 , 10 , 2) : # The step value determines the increment .


2 print ( i )
Listing 3.50: To specify a step

3.4.1 Nested For Loops


In Python and other programming languages you can use one loop inside another loop.
Syntax for nested For loops in Python:
1 for i in range (1 , 4) : # Outer loop
2 for j in range (1 , 3) : # Inner loop
3 print ( f " i ={ i } , j ={ j } " )
Listing 3.51: Syntax for nested

With each iteration of the outer loop, the inner loop runs through its entire cycle.

3.5 While Loop


In Python, The while loop statement repeatedly executes a code block while a particular
condition is true.
In a while-loop, every time the condition is checked at the beginning of the loop, and if it
is true, then the loop’s body gets executed. When the condition became False, the controller
comes out of the block.
CHAPTER 3. PYTHON PROGRAMMING 36

1 while condition :
2 body of while loop
Listing 3.52: Syntax of while-loop

Example 3.5.1. Using While Loops in Python

1 x = 1
2 while x <= 5:
3 print ( x ) # Indentation inside while loop
4 x += 1 # Increment x
Listing 3.53: Basic While Loop

The loop runs while x <= 5, then stops when x reaches 6.

Example 3.5.2. calculate the sum of first ten numbers

1 num = 10
2 sum = 0
3 i = 1
4 while i <= num :
5 sum = sum + i # Indentation inside while loop
6 i = i + 1
7 print ( " Sum of first 10 number is : " , sum ) # Printing outside the loop
Listing 3.54: calculate the sum of first ten numbers

3.6 Break Statement


The break statement is used inside the loop to exit out of the loop. It is useful when we
want to terminate the loop as soon as the condition is fulfilled instead of doing the remaining
iterations. It reduces execution time. Whenever the controller encountered a break statement,
it comes out of that loop immediately

Example 3.6.1. Using break to Exit a Loop

1 for num in range (1 , 6) :


2 if num == 3:
3 break # Stops the loop when num is 3
4 print ( num )
Listing 3.55: Using break

break terminates the loop when num == 3.

3.7 Continue Statement


The continue statement is used to skip the current iteration and continue with the next
iteration.
Let’s see how to skip a for a loop iteration if the number is 5 and continue executing the
body of the loop for other numbers

Example 3.7.1. Using continue to Skip an Iteration


CHAPTER 3. PYTHON PROGRAMMING 37

1 for num in range (1 , 6) :


2 if num == 3:
3 continue # Skips the rest of this iteration
4 print ( num )
Listing 3.56: Using continue

continue skips num == 3 and moves to the next iteration.

3.8 Functions in Python


In Python, the function is a block of code defined with a name. We use functions
whenever we need to perform the same task multiple times without writing the same code
again. It can take arguments and returns the value.
Function improves efficiency and reduces errors because of the reusability of a code. Once
we create a function, we can call it anywhere and anytime. The benefit of using a function is
reusability and modularity.

3.8.1 Types of Functions


Python support two types of functions
1. Built-in function

2. User-defined function
Built-in function
The functions which are come along with Python itself are called a built-in function or
predefined function. Some of them are listed below. range() , type() , input() etc.
User-defined function
Functions which are created by programmer explicitly according to the requirement are
called a user-defined function.

3.8.2 Creating a Function


Use the following steps to to define a function in Python.

• Use the def keyword with the function name to define a function.

• Next, pass the number of parameters as per your requirement. (Optional).

• Next, define the function body with a block of code. This block of code is nothing but
the action you wanted to perform.

Syntax of creating a function


1 def function_name ( parameter1 , parameter2 ) :
2 # function body
3 # write some action
4 return value
Listing 3.57: creating a function
Here,
• function_name : Function name is the name of the function. We can give any name
to function.
CHAPTER 3. PYTHON PROGRAMMING 38

• parameter : Parameter is the value passed to the function. We can pass any number
of parameters. Function body uses the parameter’s value to perform an action
• function_body : The function body is a block of code that performs some task. This
block of code is nothing but the action you wanted to accomplish.
• return value : Return value is the output of the function (optional).
Example 3.8.1. Creating a function with parameters and return value Functions can return
a value. The return value is the output of the function. Use the return keyword to return
value from a function.
1 # function
2 def calculator (a , b ) :
3 add = a + b
4 # return the addition
5 return add
6
7 # call function
8 # take return value in variable
9 res = calculator (20 , 5)
10
11 print ( " Addition : " , res )
12 # Output Addition : 25
Listing 3.58: A function with parameters and return value

3.8.3 Create a Function in a separate File


Here’s how you can organize your code into separate files:
Example 3.8.2. Step 1: Create a Python File (myfunctions.py) In this file, define the average
function:
1 # myfunctions . py
2 def average (x , y ) :
3 return ( x + y ) / 2
Listing 3.59: Python File myfunctions.py

Example 3.8.3. Step 2: Create Another Python File (testaverage.py) In this file, import the
average function and use it:
1 # testaverage . py
2 from myfunctions import average
3
4 # Test the function
5 num1 = 10
6 num2 = 20
7 result = average ( num1 , num2 )
8
9 print ( f " The average of { num1 } and { num2 } is { result } " )
Listing 3.60: Python File testaverage.py
How It Works
1. myfunctions.py contains the function definition.

2. testaverage.py imports the function using from myfunctions import average.


3. The function is then used in testaverage.py, and the result is printed.
CHAPTER 3. PYTHON PROGRAMMING 39

3.8.4 Functions with multiple return values


You can also return multiple values from a function. Use the return statement by separating
each expression by a comma.

Example 3.8.4. Return Multiple Values In this example, we are returning three values from
a function. We will also see how to process or read multiple return values in our code.

1 def arithmetic ( num1 , num2 ) :


2 add = num1 + num2
3 sub = num1 - num2
4 multiply = num1 * num2
5 division = num1 / num2
6 # return four values
7 return add , sub , multiply , division
8
9 # read four return values in four variables
10 a , b , c , d = arithmetic (10 , 2)
11
12 print ( " Addition : " , a )
13 print ( " Subtraction : " , b )
14 print ( " Multiplication : " , c )
15 print ( " Division : " , d )
Listing 3.61: Return Multiple Values
Chapter 4

Object Oriented Programming

In this chapter, you will learn OOP (Object Oriented Programming) in Python. OOP concepts
include object, classes, constructor and encapsulation, polymorphism, and inheritance.

4.1 What is Object Oriented Programming in Python


Object-oriented programming (OOP) is a programming paradigm based on the concept of
"objects". The object contains both data and code: Data in the form of properties (often
known as attributes), and code, in the form of methods (actions object can perform).
An object-oriented paradigm is to design the program using classes and objects. Python
programming language supports different programming approaches like functional program-
ming, modular programming. One of the popular approaches is object-oriented programming
(OOP) to solve a programming problem is by creating objects.

Figure 4.1: Python OOP concepts

An object has the following two characteristics:


• Attribute (Properties): Attributes represent the data or state of an object.

• Behavior (Methods): Behaviors represent the actions that an object can perform.

Example: Car as an Object


• Attributes (Properties):

40
CHAPTER 4. OBJECT ORIENTED PROGRAMMING 41

– name: e.g., “Toyota Camry”


– price: e.g., 30,000
– color: e.g., “Red”

• Behaviors (Methods):

– braking(): Action to stop the car


– acceleration(): Action to increase the speed

4.2 Class and Objects


In Python, everything is an object. A class is a blueprint for the object. To create an object
we require a model or plan or blueprint which is nothing but class.
For example, you are creating a vehicle according to the Vehicle blueprint (template). The
plan contains all dimensions and structure. Based on these descriptions, we can construct a
car, truck, bus, or any vehicle. Here, a car, truck, bus are objects of Vehicle class.

Object is an instance of a class. The physical existence of a class is nothing but an


object. In other words, the object is an entity that has a state and behavior.

4.3 Class Attributes and Methods


When we design a class, we use attributes and methods.
In Class, attributes can be defined into two parts:

Instance variables: Instance variables are attributes attached to an instance of a class. We


define instance variables in the constructor (the __init__() method of a class).

Class variables: A class variable is a variable that is declared inside a class, but outside any
instance method or the __init__() method.

Inside a Class, we can define the following three types of methods.

Instance method: Used to access or modify the object attributes. If we use instance variables
inside a method, such methods are called instance methods.

Class method: Used to access or modify the class state. In method implementation, if we
use only class variables, then such type of methods we should declare as a class method.
CHAPTER 4. OBJECT ORIENTED PROGRAMMING 42

Static method: It is a general utility method that performs a task in isolation. Inside this
method, we don’t use instance or class variable because this static method doesn’t have
access to the class attributes.

4.4 Creating Class and Objects


In Python, Use the keyword class to define a Class. In the class definition, the first string
is docstring which, is a brief description of the class.
The docstring is not necessary but recommended to use. We can get docstring using
__doc__() attribute. Use the following syntax to create a class .
Syntax
1 class classname :
2 ’’’ documentation string ’’’
3 class_suite
Listing 4.1: Creating Class

Documentation string: represent a description of the class. It is optional.

class_suite: class suite contains class attributes and methods

We can create any number of objects of a class. use the following syntax to create an
object of a class.
1 object_name = classname ( arguments )
Listing 4.2: Creating an object

OOP Example: Creating Class and Object in Python


1 class Employee :
2 # class variables
3 company_name = ’ ABC Company ’
4
5 # constructor to initialize the object
6 def __init__ ( self , name , salary ) :
7 # instance variables
8 self . name = name
9 self . salary = salary
10
11 # instance method
12 def show ( self ) :
13 print ( ’ Employee : ’ , self . name , self . salary , self . company_name )
14
15 # create first object
16 emp1 = Employee ( " Harry " , 12000)
17 emp1 . show ()
18
19 # create second object
20 emp2 = Employee ( " Emma " , 10000)
21 emp2 . show ()
Listing 4.3: OOP Example
CHAPTER 4. OBJECT ORIENTED PROGRAMMING 43

Output:

1 Employee : Harry 12000 ABC Company


2 Employee : Emma 10000 ABC Company

• In the above example, we created a Class with the name Employee.

• Next, we defined two attributes name and salary.

• Next, in the __init__() method, we initialized the value of attributes. This method
is called as soon as the object is created. The init method initializes the object.

• Finally, from the Employee class, we created two objects, Emma and Harry.

• Using the object, we can access and modify its attributes.

Constructors in Python
In Python, a constructor is a special type of method used to initialize the object of a Class.
The constructor will be executed automatically when the object is created. If we create three
objects, the constructor is called three times and initialize each object.
The main purpose of the constructor is to declare and initialize instance variables.The
__init__() method is called the constructor in Python. In other words, the name of the
constructor should be __init__(self)

Default Constructor in Python


A constructor in Python is optional. If a class does not define an __init__() method,
Python provides a default constructor that allows object creation. However, with the default
constructor, we must assign attributes to the object manually after creation.

Example: Using Default Constructor

1 class Employee :
2 # class variable
3 company_name = ’ ABC Company ’
4
5 # No constructor ( __init__ ) defined
6
7 # instance method
8 def show ( self ) :
9 print ( ’ Employee : ’ , self . name , self . salary , self . company_name )
10
11 # create first object using default constructor
12 emp1 = Employee ()
13 emp1 . name = " Harry "
14 emp1 . salary = 12000
15 emp1 . show ()
16
17 # create second object
18 emp2 = Employee ()
19 emp2 . name = " Emma "
20 emp2 . salary = 10000
CHAPTER 4. OBJECT ORIENTED PROGRAMMING 44

21 emp2 . show ()
Listing 4.4: Using Default Constructor

Output

1 Employee : Harry 12000 ABC Company


2 Employee : Emma 10000 ABC Company

4.5 Encapsulation in Python


Encapsulation is an object-oriented programming principle that binds data (attributes) and
methods that operate on the data within a class. It restricts direct access to some of the
object’s components, which helps in data protection. In Python, this is done using private
and protected access modifiers.

• Public: Accessible from anywhere (self.name)

• Protected: Prefixed with a single underscore ( _name) — meant for internal use within
the class or subclass

• Private: Prefixed with double underscores ( __name) — makes the variable hidden and
not directly accessible from outside the class

Example

1 class Person :
2 def __init__ ( self , name , age ) :
3 self . name = name # public
4 self . _age = age # protected
5 self . __salary = 5000 # private # not accessible outside of a
class
6
7
8 def show_info ( self ) :
9 print ( " Name : " , self . name )
10 print ( " Age : " , self . _age )
11 print ( " Salary : " , self . __salary )
12
13 p = Person ( " Alice " , 30)
14 p . show_info ()
15
16 # access info from outside of a class
17 print ( p . name ) # Accessible
18 print ( p . _age ) # Accessible ( but discouraged )
19 # print ( p . __salary ) # Not accessible directly ( raises error )
20 print ( p . _Person__salary ) # Accessing private via name mangling

Output

1 Name : Alice
2 Age : 30
3 Salary : 5000
4 Alice
CHAPTER 4. OBJECT ORIENTED PROGRAMMING 45

5 30
6 5000

4.6 Inheritance In Python


In an Object-oriented programming language, inheritance is an important aspect. In Python,
inheritance is the process of inheriting the properties of the parent class into a child class.
The primary purpose of inheritance is the reusability of code. Using inheritance, we can
use the existing class to create a new class instead of recreating it from scratch.

Syntax

1 class BaseClass :
2 Body of base class
3 class DerivedClass ( BaseClass ) :
4 Body of derived class
Listing 4.5: Inheritance In Python

4.6.1 Single Inheritance


In single inheritance, a child class inherits from a single-parent class. Here is one child class
and one parent class.

Example 4.6.1. Example Let’s create one parent class called Vehicle and one child class
called Car to implement single inheritance.
CHAPTER 4. OBJECT ORIENTED PROGRAMMING 46

1 # Base class
2 class Vehicle :
3 def Vehicle_info ( self ) :
4 print ( ’ Inside Vehicle class ’)
5
6 # Child class
7 class Car ( Vehicle ) :
8 def car_info ( self ) :
9 print ( ’ Inside Car class ’)
10
11 # Create object of Car
12 car = Car ()
13
14 # access Vehicle ’s info using car object
15 car . Vehicle_info ()
16 car . car_info ()
Listing 4.6: Single Inheritance

1 Inside Vehicle class


2 Inside Car class

4.6.2 Hierarchical Inheritance


In Hierarchical inheritance, more than one child class is derived from a single parent class. In
other words, we can say one parent class and multiple child classes

Example 4.6.2. Example Let’s create ‘Vehicle’ as a parent class and two child class ‘Car’ and
‘Truck’ as a parent class.

1 class Vehicle :
2 def info ( self ) :
3 print ( " This is Vehicle " )
4
5 class Car ( Vehicle ) :
6 def car_info ( self , name ) :
7 print ( " Car name is : " , name )
8
9 class Truck ( Vehicle ) :
10 def truck_info ( self , name ) :
11 print ( " Truck name is : " , name )
12
13 obj1 = Car ()
14 obj1 . info ()
CHAPTER 4. OBJECT ORIENTED PROGRAMMING 47

15 obj1 . car_info ( ’ BMW ’)


16
17 obj2 = Truck ()
18 obj2 . info ()
19 obj2 . truck_info ( ’ Ford ’)
Listing 4.7: Hierarchical Inheritance

1 This is Vehicle
2 Car name is : BMW
3
4 This is Vehicle
5 Truck name is : Ford

4.6.3 Python super() function


When a class inherits all properties and behavior from the parent class is called inheritance.
In such a case, the inherited class is a subclass and the latter class is the parent class.
In child class, we can refer to parent class by using the super() function. The super
function returns a temporary object of the parent class that allows us to call a parent class
method inside a child class method.

Benefits of using the super() function.


We are not required to remember or specify the parent class name to access its methods.
We can use the super() function in both single and multiple inheritances. The super()
function support code reusability as there is no need to write the entire function.
1 class Company :
2 def company_name ( self ) :
3 return ’ Google ’
4
5 class Employee ( Company ) :
6 def info ( self ) :
7 # Calling the superclass method using super () function
8 c_name = super () . company_name ()
9 print ( " Jessa works at " , c_name )
10
11 # Creating object of child class
12 emp = Employee ()
13 emp . info ()

Output

1 Jessa works at Google

In the above example, we create a parent class Company and child class Employee .
In Employee class, we call the parent class method by using a super() function.

4.6.4 Method Overriding


In inheritance, all members available in the parent class are by default available in the child
class. If the child class does not satisfy with parent class implementation, then the child class
is allowed to redefine that method by extending additional functions in the child class. This
concept is called method overriding.
CHAPTER 4. OBJECT ORIENTED PROGRAMMING 48

When a child class method has the same name, same parameters, and same return type
as a method in its superclass, then the method in the child is said to override the method in
the parent class.

1 class Vehicle :
2 def max_speed ( self ) :
3 print ( " max speed is 100 Km / Hour " )
4
5 class Car ( Vehicle ) :
6 # overridden the implementation of Vehicle class
7 def max_speed ( self ) :
8 print ( " max speed is 200 Km / Hour " )
9
10 # Creating object of Car class
11 car = Car ()
12 car . max_speed ()

Output

1 max speed is 200 Km / Hour

In the above example, we create two classes named Vehicle (Parent class) and Car
(Child class). The class Car extends from the class Vehicle so, all properties of the parent
class are available in the child class. In addition to that, the child class redefined the method
max_speed() .

4.7 Polymorphism
Polymorphism in OOP is the ability of an object to take many forms. In simple words,
polymorphism allows us to perform the same action in many different ways.
Polymorphism is taken from the Greek words Poly (many) and morphism (forms). Poly-
morphism defines the ability to take different forms.
For example, The student can act as a student in college, act as a player on the ground,
and as a daughter/brother in the home.
CHAPTER 4. OBJECT ORIENTED PROGRAMMING 49

Example: Using Polymorphism in Python


For example, In the below example, calculate_area() instance method created in both
Circle and Rectangle class. Thus, we can create a function that takes any object and calls
the object’s calculate_area() method to implement polymorphism. Using this object can
perform
Polymorphism with class methods is useful when we want objects to perform the same
action in different ways. In the below example, both objects calculate the area (same action)
but in a different way (different formulas)
1 class Circle :
2 pi = 3.14
3
4 def __init__ ( self , redius ) :
5 self . radius = redius
6
7 def calculate_area ( self ) :
8 print ( " Area of circle : " , self . pi * self . radius * self . radius )
9
10 class Rectangle :
11 def __init__ ( self , length , width ) :
12 self . length = length
13 self . width = width
14
15 def calculate_area ( self ) :
16 print ( " Area of Rectangle : " , self . length * self . width )
17
18 # function
19 def area ( shape ) :
20 # call action
21 shape . calculate_area ()
22
23 # create object
24 cir = Circle (5)
25 rect = Rectangle (10 , 5)
26
27 # call common function
28 area ( cir )
29 area ( rect )
Listing 4.8: Example: Using Polymorphism in Python

Output

1 Area of circle : 78.5


2 Area of Rectangle : 50

You might also like