Cours Python Prohramming23
Cours Python Prohramming23
Faculty of Technology
Department of Electrical Systems Engineering
Python Programming
Lecturer: Dr.Nekkaa
Email: [email protected]
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
iii
Chapter 1
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.
• 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
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.
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.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.
• Text Editors: Simple, lightweight tools with basic features like syntax highlighting.
Examples include Notepad++, Sublime Text, and Visual Studio Code.
• Online Editors: Web-based editors that require no installation. Examples include Replit
and Google Colab.
For beginners, this package is sufficient for basic Python programming (see Figure 1.1).
However, for more advanced Python development, you will likely need:
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.
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.
Example 1.8.1. Hello World Example Lets open your Python Editor and type the following:
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
To enter Python’s interactive mode, simply type python and press Enter. This will launch
the Python interpreter. (See Figure ??.)
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).
• Click File → New File, or open an existing script with File → Open....
• Click File → Save As... and save it with a .py extension (e.g., script.py).
As shown in Figure 1.4, you can enter multiple Python commands, which together form
a complete Python program.
To execute the script, use Run → Run Module or press F5, as shown in Figure 1.5.
• Use the cd command to change to the folder where your script is located:
1 cd C :\ Users \ YourUsername \ Documents \ PythonScripts
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.
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. Open Spyder
• Launch Spyder from the Anaconda Navigator or by running spyder in the com-
mand prompt.
• Click File → Save As... and save the script with a .py extension.
Example 2.1.1. Hello World Example Lets open your Python Editor and type the following:
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.
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
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
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.
• 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
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
• Provides specialized tools for scientific computing, data visualization, and more.
Disadvantages:
• 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
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.
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.
• == equal to
• != not equal to
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
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 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
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.
• 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
• Using indexing, we can access any item from a list using its index number
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.
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.
• 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.
• Reverse a list
Example 3.2.2.
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 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
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.
• 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
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.
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.
As seen in the above example the items are sorted in the ascending order.
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.
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
Example 3.4.1. Using range() in a For Loop The range() function generates a sequence of
numbers.
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
With each iteration of the outer loop, the inner loop runs through its entire cycle.
1 while condition :
2 body of while loop
Listing 3.52: Syntax of while-loop
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
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
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.
• Use the def keyword with the function name to define a function.
• Next, define the function body with a block of code. This block of code is nothing but
the action you wanted to perform.
• 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
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.
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.
In this chapter, you will learn OOP (Object Oriented Programming) in Python. OOP concepts
include object, classes, constructor and encapsulation, polymorphism, and inheritance.
• Behavior (Methods): Behaviors represent the actions that an object can perform.
40
CHAPTER 4. OBJECT ORIENTED PROGRAMMING 41
• Behaviors (Methods):
Class variables: A class variable is a variable that is declared inside a class, but outside any
instance method or the __init__() method.
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.
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
Output:
• 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.
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)
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
• 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
Syntax
1 class BaseClass :
2 Body of base class
3 class DerivedClass ( BaseClass ) :
4 Body of derived class
Listing 4.5: Inheritance In Python
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
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
1 This is Vehicle
2 Car name is : BMW
3
4 This is Vehicle
5 Truck name is : Ford
Output
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.
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
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
Output