0% found this document useful (0 votes)
5 views62 pages

Python Programming Concepts Overview

Uploaded by

lolawowo1440
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)
5 views62 pages

Python Programming Concepts Overview

Uploaded by

lolawowo1440
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

Object -Oriented Programming :

Chapter 2: Python Programming Concepts

USTHB/ FGE/ Department of Telecommunications


Master's in Networks and Telecommunications

Prof. H. Nemmour

2025/2026

1
Introduction

The goal of this chapter is to learn how to use variables and


the instructions needed for programming in Python. We will
explore Python's composite variables such as lists, strings, and
dictionaries. We will cover execution control instructions and
function design in Python.

2
Python Reserved Words and Functions

There are 33 reserved words in Python:

3
Predefined Functions

• The print() function: Allows you to display one or more variables of different
types and sizes.

Example:

4
Predefined Functions
• The input() function: Provides user interaction. It allows you to enter the value you
want to assign to a variable.

 Example : here input puts the value entered by the user into a course variable .

 Note: All user input is of type string (str). If an integer is entered, we must convert to
int before using the variable. If A=input() is entered and the user enters 2, we must
use A=int(A). Similarly, for float, if 2.5 is entered, we set A= float (A).
5
Variable Typing

Unlike C++ and Java, where data typing is static (meaning that each data

item must be declared with a specific type upon creation), in Python,

typing is dynamic. This means that if you want to create three variables of

type int, string, and float, you simply specify the variable name and make

an assignment. Python chooses the appropriate type for the data item

based on the value provided by the user.

6
Variable Typing
Example: We declare the following variables in the command line:

Variable names:
alphanumeric

Each variable is
an Object

7
Operators and expressions

• In Python, it is possible to combine variables and their values into a single


expression. For example, we can write: A, B, C=3, 4.5, 'course', and the
compiler will create three variables such as:
A=3, B=4.5, C='course'.

• In addition to the classic operators: +, -, /, *, Python uses other operators


namely: % (Modulo or remainder of the division), ** (Power: 2**3=8), //
(Integer division), and E (Exponent: 2E5= 2*10**5=20000).

8
Execution flow control
Like other languages, a program's instructions are executed one after the
other, in the order they were written. However, it is possible to control the
execution of these instructions according to the program's needs.
Conditional execution: if, if else, if elif:

Only one condition


A single condition
and its negation
Two conditions and a
negation
9
Execution flow control
Comparison operators:
Operator Function
A>B Check if A is greater than B
Noticed:
A>=B Check if A is greater than or equal to B Do not mix the == operator which checks
A<B Check if A is smaller than B if A is equal to B with the assignment
A<=B Check if A is less than or equal to B
A=B which assigns the value of B to A.

A!=B Check if A is different from B


A==B Check if A is equal to B

Example :

10
Compound statements or statement blocks

All the statements we have used if , elif , else and others ( for , while , try , ….) can
control the execution of a block composed of several statements.

Example :

11
Repeat Loops

Repeat loops allow a block of instructions to be re-executed several times depending


on the execution needs.
For loop:
It can be used through an iterator such as:

Arange function of
the numpy module 12
Repeat Loops

While loop:
Condition the execution of a block of instructions on the value of a variable.

13
Repeat Loops

Break and continue:


It is possible to perform execution by repetition in a finite loop (like for) or
infinite loop (like while True ) and control repetition by other instructions,
namely, break and continue. Break stops program execution; while continue
stops the current iteration.

14
Exception handling instruction

Try, except, finally:


Exception handling can be achieved by specific instructions, namely:
• try : Checks a block of statements for errors and executes it if the
code is error-free.
• except: allows error handling, it executes if the compiler finds an
error in the block controlled by try.
• finally: this is a block that is executed regardless of the result of try
and except.

15
Exception handling instruction

Example:

16
String: Character strings

Strings are a composite data type. A string can be considered a single object, or
multiple objects.
 Example:

We can use a for


17
String: Character strings
The String class has several methods for manipulating string objects. These include the
following:

18
String: Character strings

Several other functions are available such as: [Link] ( ) or [Link] () which convert the
string C to lowercase or uppercase letters.
[Link] ()/ [Link] (): Checks if all characters in C are letters or numbers.
String slices:
Like all other containers, the contents of a string can be accessed in several ways:
C[2:] : takes the characters from the third to the last
C[1:5] : takes characters 1,2,3 and 4.
C[-1] : last character of the string
C[-3:] : the last three characters
C[:-3] : all characters except the last three

19
String: Character strings

 Operations on the strings:

Concatenation of a string:

Repeating a string:

20
Composite Variables: Lists

A list is an ordered collection of objects


accessible using an index.
A list can contain multiple data types: str, int,
float, list. Data can have different dimensions:
single variable, 1-dimensional array, multi-
dimensional array, objects, etc.

21
Composite Variables: Lists

Lists are objects, and therefore have methods (or programs) that allow them to be
manipulated. Among these functions, we distinguish:

Append(X) Add X to the end of the list


Sort ( ) Sort the elements of a list (from smallest to largest)
Reverse ( ) Reverse the order of the elements
Index (x) Find the position of X
Remove (x) Delete the first element with value X
Insert(i,x) Insert X at position i
Extend(L2) Add all elements of list L2
Pop([i]) Delete the element located at position i

22
Composite Variables: Lists

Console
Python code

23
Composite Variables: Lists

Finally, to iterate through a list, we


can use the for statement and the
range( ) and len( )

 Observation:
It is possible to perform operations on lists similarly to strings.
The + allows you to concatenate 2 lists, the * allows you to duplicate them.

24
Composite variables: Tuples

Tuples are another type of composite variable in Python, similar to lists but not
modifiable. A tuple is a comma-separated collection of elements.

 Example:
Z = 'A', 'B', 2, 7.8, 'word' , the console displays:

 Note that:
tuples are immutable, their elements cannot be modified, nor can the del or
remove functions be applied to them. This property makes them very rarely
used compared to lists.
25
Composite variables: Sets

A Set is a python container that is  Example:


unordred ensemble of variables. Its
main property is the fact that it doen’t
allow values duplications. This means
that a Set cannot contain two elements
with the same value. It is mainly used
to extract non-duplicated elements of
another python container such as
distinct words composing a text, or
dinstinct numbers composing a numpy
array.
26
Composite variables: Sets

 Example: Results after code execution

27
Composite variables: Sets

 Example: Extract distinc values composing a numpy array

28
Composite Variables: Dictionaries

All the composite data types we've seen (strings, lists, tuples) are sequences of
data. Therefore, it is possible to scan them by an integer index to move from
one element to another, because the location of these variables in memory is
done by successive addresses. In advanced programming, it is possible to work
with a collection of non-sequential elements, and therefore, the positions in
memory are not located one after the other. This makes scanning these
variables by an integer index impossible. These are, in fact, so-called dictionary
variables. A dictionary is a modifiable collection but is not sequential.

29
Composite Variables: Dictionaries

Accessing dictionary elements: To access any element of a dictionary, we


use a special index called a key . The key is of alphabetical or numeric
type. Dictionary elements can be of any type: numeric, string, list, tuple,
dictionary, function, and even a class.

Creating a dictionary:
In the dictionary, each element is a pair composed of a key (index) and its
value.

30
Composite Variables: Dictionaries

Create a dictionary:
In the dictionary, each element is a pair composed of a key (index) and its value.

31
Composite Variables: Dictionaries

Manipulate a Dictionary :
To manipulate a dictionary, we always use keys. For example, to
display an item, we use its key.
Noticed:
1. The append function is not necessary because the dictionary is
not a sequence. Simply add the new element with its key:
dic[2]= 'Second cycle'
2. When displayed, the key and value are separated by ' : '
3. To delete an element we use del with the key: del(dic[1]) or del
dic[1]

32
Composite Variables: Dictionaries

Manipulate a Dictionary :
len() function is built into dictionaries to retrieve the number of elements. There is
also the keys() method, which returns the list of keys, and values() , which returns the
values.
Membership test: Like lists, strings and tuples, to check the existence of an element in
the dictionary we use the if statement :

33
Composite Variables: Dictionaries

len, keys, and values


functions:

for loops :

[Link]() returns the tuple


(key, value)

34
Composite Variables: Dictionaries
get function :
This function returns the value of the
key searched for in the dictionary. If
this key is not part of the dictionary,
the function returns None. It is
possible to choose the value to
return as an option:

[Link] ('T', 0): if the key T does not


exist, the function returns 0,

35
Arrays: Numpy Module

In Python, modules are packages of programs (often organized into classes),


offering algorithms specific to a domain of application. The number of these
modules is large, and we will use them according to our needs. The Numpy
module is the main one for all applications, because it allows you to create array
objects, such as vectors and matrices, and offers a series of functions that allow
you to manipulate them. Like all other modules, Numpy can be imported by:
import numpy or import numpy as np ( to use the name np for the object instead
of numpy ).
Import creates an object of the numpy module. All numpy functions can be
accessed through the object.
36
Arrays: Numpy Module

 Create numpy arrays:


To create an empty numpy array, we must choose its size, and call the
instruction [Link] () (or [Link] to initialize to 0) as follows:

37
Arrays: Numpy Module

 Remarks:
Many times we don't know the size of the vector or matrix that will contain our
data, so we use a list T to collect the data, and once the processing is finished,
we can convert the list into a numpy array N by the following instruction:
N=[Link](T). In this case, the elements of the list T must have the same type.
In a two-dimensional array, the first dimension corresponds to the number of
rows and the second corresponds to the number of columns.
 Example:

38
Arrays: Numpy Module

Some properties of numpy arrays:

[Link] Dimension of D (in the example we get 2)


[Link] Gives the number of rows and columns of D
[Link] Gives the number of elements in D (5*15=75 in the example)
S=[Link](15,5) create an array S by changing the positions of the elements of D.
H=D.T H is the transpose of D
Z=[Link]() Z is a copy of object D
C=[Link](A,B) Vector product between A and B (equivalent to: sum(A*B))
C=[Link]([2, 2]) Create an empty 2*2 matrix
Z=np.zeros_like(D) Create an array Z initialized to zero and of size equal to that of D
A=[Link](0,10) Create a vector of 10 elements ranging from 0 to 9
Z=[Link](4) Create a 4*4 identity Z matrix
A=[Link]((3, 3), 5) Create a 3*3 matrix A filled with the value 5
39
Arrays: Numpy Module

The functions applied to numpy objects are very numerous, we


distinguish: [Link], [Link] , [Link],
[Link] , [Link], [Link], [Link], ….

For details, see the numpy website : [Link]

40
Functions in Python

Introduction:
In the previous sections, we saw two types of functions: Predefined
functions like print(), input(), and len(), and functions that belong to the
various modules (libraries) that can be imported into Python. The latter
allow you to perform tasks specific to the objects of their classes. However,
the user is often led to build their own function to optimize their program.
The role of the function is to encompass a program that is repeated several
times during execution. So, instead of rewriting it several times, we put it
in a function that will be called as needed.

41
Functions in Python

Remark:
To exploit the functions of a module, we must import the module into our
spyder “.py” or jupiter file «. ipynb » . Importing creates a variable called an
object that represents the module and can call all its functions, as follows:

Import random as rd # rd the name of the random object

A=[Link](10, 50) # call the randint function to generate a value between 10


and 50.

42
Functions in Python

User created function:


The Python syntax for creating a function is as follows:
def Function_name( parameters ) :
instructions block
…………….

Note that :
• The user must choose the name of his function (a name different from
the names taken by the predefined functions in Python).
• The number of parameters depends on the user (one can have a
function without parameters).
• The size and type of parameters are set by the user: simple variable,
list, vector, matrix, object, int , string, float, list, etc. 43
Functions in Python
Example: Function without parameters The execution of the function code is done to
compile the function content. It is not an
execution of the code

To execute the function code, you


need to make a call

44
Functions in Python

Remarks :
• The variable a does not appear in the list of Python variables
because it is local to the function. Local variables of a function
are variables defined inside the function; they are created
when the function is called and deleted when the function's
program finishes executing.
• A variable is said to be global if it is created outside of any loop
or function in the program. It is a variable visible to all parts of
the program.

45
Functions in Python

Example: Function with parameters The execution creates A, B, and C and


passes the codes of the functions Fonct,
and funct2 to the compiler.
Fonct will receive two parameters of
numpy vector types, but the type and

This code can be replaced names are not specified in the function
by: C = x ∗ y
to make it applicable to any pair of
vectors.
function2 , receives a vector and a
parameter.
For execution, a call must be made
through concrete variables.
46
Functions in Python

Example: Function with parameters


Calling functions through concrete
variables already defined in our
code

47
Functions in Python

Please note:

• When writing the function code, symbolic parameters are used (not
necessarily the same names as the variables to be passed to the function).
• The typing of the parameters is dynamic, it is done during the first call of
the function.
• It is possible to assign default values to the parameters of a function. The
default value will be used if a value is not assigned to the respective
parameter during the call.

48
Functions in Python

Example :

Call with
default values

49
Functions in Python

Overloading a function:

Function overloading in classical programming like C++,


consists of defining multiple functions with the same
name but different signatures. The signature of a
function is the name + its arguments (its parameters). In
Python, overloading is different, it is possible to create
multiple functions with the same name, but the
compiler only keeps the last one.

50
Functions in Python

Overloading a function:

overloading in Python is allowed in class inheritance (Chapter 4), where derived


classes can overload the functions of the base class to add some specific
processing.
Furthermore, it is possible to create a single function that can be called in multiple
ways, using parameters with default values.

51
Functions in Python
Transferring variables to a function:

When you pass a variable as a parameter to a function, any changes made to that
variable by the function's code are only visible inside the function. This is because
the compiler sends a copy of the variable, not the variable itself.

Example:

52
Functions in Python

Transferring variables to a function:

Python offers the ability to define a function that can


accept an arbitrary number of parameters. The
parameters will be defined when the function is
called, as shown in the example opposite.

53
Switch Case statement

Case:
This instruction is employed to avoid
the multiple use of if-else-elif
instructions. It allows to match codes
to the value of a given argument.
This intruction is available in python
3.10.
Call and Output

54
Function with the Switch Case statement

Case:
The case statement can be used to
control the call of various functions
(or objects beloging to different
classes, or more complicated codes).

Call and output

55
Zip function
Zip:
This function takes several iterables (tuples, lists, strings) and aggregates their
combination as joined iterators. For instance, if we have two lists that contain
names and IDs of students, the Zip function allows performing iterations over
the two lists at once.

Zip takes the shortest


input iterable

56
Enumerate function

Enumerate: (Syntax : enumerate(iterable , start=0))


This function adds a counter to an iterable and returns the resulting iterable
object.

57
Filter function

Filter: (Syntax: filter(fct, iterable))


It extracts elements from an iterable that respect a certain condition by using a
function fct.
Instead of using a for loop with the if instruction, filter allows an automatic
selection of desired elements as depicted in the following code:

The function fct


selects even values

58
Filter function

Lambda function :
Since we aim to perform a short operation, it is possible to used inline functions
like the lambda function, which is a small functiondefined by the keyword lambda
instead of def. It is restricted to a single instruction and is commonly passed as an
argument in high order functions like, filter, map and sorted. The precedent code
of the filter function can be rewritten as follows:

59
Map function

Map: (Syntax: map(fct, iterable))


It applies a function fct to each element in the iterable.

Other examples :

60
Sorted function
Sorted : (Syntax: sorted(iterable, key, reverse))
It performs a sort of the element composing an iterable
key: change the order nature (like the size for strings)
Reverse: Flase as default corresponding to sort ascending, while True
corresponds to sort descending.

61
Conclusion

In this chapter, we learned the fundamental concepts for


developing programs in Python, such as variables, repetition and
flow control instructions , and functions. However, to perform
advanced scientific programming, it is necessary to organize
codes into classes so that they can be manipulated through
objects. Thus, in the next chapter, we will discuss the concept of
a class and its objects.

62

You might also like