Signature Universelle in Python

Course Objectives

  • Introduce basic concepts of Python 3.
  • Learn to program using Python.
  • Master standard Python containers.
  • Introduce students to Python functions.

Course Organization

  • Course: 30 hours.
  • Practical Work: 15 hours.
  • Evaluation: TP/DS/Exam.
  • Classroom: Python Programming (CODE: brjh3fp).

Course Plan

  • Fundamentals of Python.
  • Standard Python Containers.
  • Functions.
  • Numerical Simulation with NumPy.
  • Graphic Visualization with Matplotlib.

Introduction to Python

  • Created in 1991 by Guido van Rossum.
  • Open source and interpreted language.
  • Dynamically typed and versatile.
  • Supports multiple paradigms: Imperative, Object-Oriented, Functional, Scripting, Concurrent, Event-Driven.

Development Environments (IDEs)

  • PC: Eric, SPYDER, IDLE, PyCharm, Thonny, PyDev, Atom
  • Jupyter Notebook: Combines IDE and presentation tool.
  • Visual Studio Code: Requires Python and Jupyter Notebook extensions.
  • Google Colaboratory: Cloud environment with free computing resources.

Jupyter Notebook

  • Creating New Notebook: File → New File, then File → Save.
  • Markdown: Used for formatting text (bold, italics, links, titles, math formulas).

Python Fundamentals

Comments

  • Used to explain code, document authorship, or disable lines.
  • Single-line comments: #.
  • Multi-line comments: """ """.

Variables

  • Characterized by name, identifier (id(var)), type (type(var)), and value.
  • Variable names can include lowercase letters (a→z), uppercase letters (A→Z), numbers (0→9), and underscores (_).
  • Reserved words cannot be used as variable names.
  • Python is case-sensitive.

Data Types

  • int: Integer (e.g., type(20)).
  • float: Floating-point number (e.g., type(12.2)).
  • bool: Boolean (True or False).
  • NoneType: Represents null value (e.g., type(None)).
  • str: String (e.g., type("ABC")).
  • complex: Complex number (e.g., type(2+4j)).

Operators

  • Comparison: <, <=, >, >=, ==, !=, is, is not.
  • Arithmetic: +, -, *, /, **, //, %.
  • Logical: or, and, not, ^ (exclusive or).

Operator Precedence (Highest to Lowest)

  • Parentheses: (expressions...)
  • Exponentiation: **
  • Multiplication, Division, Quotient, Remainder: *, /, //, %
  • Addition, Subtraction: +, -
  • Comparisons: <, <=, >, >=, <>, !=, ==
  • Negation: not
  • And: and
  • Or: or

Multiple Assignment

  • x,y=11,22 ; x,y=y,x ; print(x,y) (;) Allows grouping instructions on the same line!

Output Instruction: print()

  • print("Bonjour")
  • print("Bonjour", end=""): Removes newline.
  • print("Bonjour", "Taoufik", sep="-"): Adds separator between arguments.

Input Instruction: input()

  • Prompts user for input from the keyboard; returns a string.

Type Conversion

  • float(33): int → float
  • int(100.9): float → int
  • str(112): int/float → string
  • eval("12.3"): str → appropriate type

Formatted Output

  • f-string method: #L'âge de l'étudiant Ahmed est 29. Sa moyenne est 12.65
  • .format() method: allows better organization of variable display

Control Flow

Conditional Statement: if

  • if <expression>: Treatment
  • if <expression>: Treatment else: Treatment
  • if <expression>: Treatment elif <expression>: Treatment else: Treatment

Loop Instruction: while

  • Executes a block of code as long as a condition is true.
  • while <expression>: Instruction(s) à répéter

Loop Instruction: for

  • Iterates over a sequence (string, list, tuple, set, dict).
  • for <element> in <sequence>: Instruction(s) à répéter
  • range(val): Enumerates integers from 0 to val-1.
  • range(val1, val2): Enumerates integers from val1 to val2-1.
  • range(val1, val2, val3): Enumerates integers from val1 to val2-1 with step=val3.

Break & Continue

  • break: Exits the loop.
  • continue: Skips to the next iteration.

Loop-End Instruction Block

  • else: Executes if the loop exits without a break.

Modules

  • Packages containing modules.
  • Modules are .py files containing variables, functions, and classes.

Importing Modules

  • import nom_module
  • from nom_module import *
  • from nom_module import fct1, classe1, ...
  • import nom_module as nomLocal

Standard Modules

  • math: Math functions.
  • datetime: Date and time manipulation.
  • json: JSON encoding and decoding.
  • os: OS-dependent functionalities.
  • re: Regular expression matching.
  • random: Random number generation.
  • csv: CSV file reading and writing.
  • sys: System variables access.

Math Module

  • exp(x)
  • factorial(x)
  • log2(x)
  • sqrt(x)
  • ceil(x)
  • floor(x)

Random Module

  • randint(a,b): Integer in [a, b].
  • randrange(a,b): Integer in [a, b[.
  • random(): Float in [0.0, 1.0[.
  • uniform(a,b): Float in [a, b[.

Standard Containers

Sequences

  • Ordered containers indexed by integers.
  • Strings (str), Lists (list), Tuples (tuple).

Sets (set)

  • Unordered containers of unique elements.
  • No indexing.

Dictionaries (dict)

  • Associative arrays (key-value pairs).

Mutable vs. Immutable

  • Mutable: Value can be modified without changing ID (list, set, dict).
  • Immutable: Value cannot be changed after creation (bool, int, float, tuple, str).

Strings (str)

  • Represent non-numeric information.
  • Enclosed in single quotes ' ', double quotes " ", or triple quotes """ """.

Access and Slicing

  • ch[index]
  • ch[ind1:ind2] (ind1 to ind2-1).

Operations

  • Concatenation and Repetition: +, *.
  • Immutability: Strings cannot be modified in place.
  • len(ch)
  • ch.lower() / ch.upper() / ch.title() / ch.capitalize() / ch.swapcase()
  • ch.count(sch)
  • sch in/not in ch
  • ch.startswith(sch)
  • ch.find(sch) / ch.index(shr)
  • ch.isupper() / ch.islower()
  • ch.split() / ch.split(sep) / ch.replace(sch1, sch2) / ch.strip() / ch.isdigit()

Lists (list)

  • Mutable series of values of different types.
  • Defined by [] or list().

Access and Slicing

  • Similar to strings.

Operations

  • len(lis) / min(lis) / max(lis) / sum(lis) / lis.count(elem) / sample(seq, n) / shuffle(lis)
  • el in lis/el not in lis
  • lis.append(elem) / lis.insert(ind, elem) / lis.extend(seq) / lis.sort() / sep.join(lis)
  • lis.remove(elem) / del lis[i:j:k] / lis.pop() / lis.pop(i) / lis.reverse()

Shallow vs. Deep Copy

  • Shallow Copy: Creates new list with references to original objects; changes to internal objects affect the copy.
  • Deep Copy: Creates new list and recursively copies all internal objects; changes to internal objects do not affect the copy.

List Comprehension

  • liste = [<expression> for <element> in <iterable> if <condition>]

Tuples (tuple)

  • Similar to lists but immutable.
  • Use () instead of [].

Operations

  • len(tup) / min(tup) / max(tup) / tup.count(elem) / tup.index(elem) / sep.join(tup)

Packing and Unpacking

  • Automatic packing: t = 2, 5, 7.
  • Automatic unpacking: a, b, c = t.

Sets (set)

  • Collection of unique, unordered objects.
  • Defined by {} or set() (for empty sets).
  • Contains only hashable objects.

Operations

  • len(ens) / max(ens) / min(ens) / sum(ens)
  • ens.add(elem) / ens.update(it1, it2, ...) / ens.remove(elem) / ens.pop() / ens.copy() / ens.clear()
  • elem in ens / elem not in ens / comparisons / ens1.union(ens2) / ens1.intersection(ens2) / ens1.difference(ens2)

Dictionaries (dict)

  • Key-value pairs.

  • Defined by {} or dict().

    Access

    • dic[key] or dic.get(key).

Operations

  • dic.clear() / dic.copy()
  • dic[cle] = val / dic.update({cle: val})
  • dic.pop(cle)
  • dic.items() / dic.keys() / dic.values()

Functions

Used to structure programs and reuse code

Defining a Function

def ():
Instructions
return value(s)
Tabulation

def f(a,b):
if a>5:
return a+b

Calling a function

()
-Arguments are the input that has been passed within the function invocation.

Function properties

-If there a matching arguments with optional parameters, their values will be adapted, else they will maintain default parameters
-An argument can be positional or named whether that is for optional or obligatory parameter.
-The passed obligator parameter arguments must be provided during the invocation of the function.
-Positional arguments must be provided before named arguments

Extensible arguments

def fun(*args):
print(args)

Converts positional arguments into a tuple.

Or

def fun(**args):
print(args)

Converts named arguments into a dictionary.

*Extensible arguments must always be declared last in a signature.

Starred signature

Signature that accepts all types of arguments, passed no matter the way.

**kwargs : Is generally the argument for storing extensible parameter

Variable scope

Local variable

Created in a function that is inaccessible outside of the function.

GLobal Variable

Are created in a main programme outside of a created function, it is visible everywhere in the script.
To change a global variable within a function the *global keyword must be used.

Annonymous functions

lambda par1, par2, ..., parN:instruction
-short and practical, but limited to a single function (Generally used for simplification

Nattive functions

map, filter ,zip

Iter=map(fct,it) : Appliques the argument function to all the values in the iterable it , and returns a list (Can be cast to other iterables)
Iter = filter(fct ,it) : Creates a list containing the elements of the iterable that fulfil the function’s conditon.
Iter = zip (it1,it2,…)Combines iterables into a single sequence of tuples.

Help

Help(fct) : shows the function’s signature and documentation.

Numpy

Numerical Python open source, can create and perform operations on arrays.

Properties:

Taille T.shape Dimensions of the elements
Dimension T.ndim No. dimensions
Nombre d’élements T.size No. Elements
Longeur len(T) length
Type de données T.dtype

Constants

 np.zeros([a,b,…]) creates an array with all elements being zero
 np.ones([a,b,…]) creates an array with all elements being one
np.full([a,b,…],val) creates an array filled with the value val
np.Eye([val) creates an identify matrix with val the size of the axises

Random value generation

np.random.random([a,b,…]) creates an array of size a,b .. and values filled with random values in the range]0,1[

np.random.randint(v1, v2, [a,b,…]) creates an array of size a,b, filled with values ranging in the interval [v1,v2[
numpy.arange(start=0, stop, step=1) builds a ndarray of dimension 1 from a sequence that starts by start and ends by stop-1 by step of step
numpy.linspace(start, stop, nb) builds a ndarray of dimension 1 from a sequence of nb values uniformely spaced between start and stop
numpy.array(lis) builds a ndarray from a list

Change in shape and dimensions:
numpy.reshape(tab, [a,b,…])converts an numpyArray (Must be single dimensionnal) into a new N dimension NumpyArray
numpy.Resize works the same
numpy.Travel reduces a multidimensional array into one with a single dimension
numpy.transpose or the  T, returns the transposed matrix
type conversion
ndarray.astype(“type”) used to convert a numpyArray into a NumpyArrray of a new specified format, but type has to be specified:

'i' 'uint8'/ 'int'/ 'int32'/ 'int64’
'f' 'float'/ 'float32'/ 'float64’
'O' object
'S' string : chaîne + codage (utf-8 par exemple)
'U' unicode string : chaîne non-codée

Acessing and slicing

Similar to other iterables with indexes starting from 0, reverse from starting from -1 etc.

Addition/Multioplication

numpyArray * Constant = NewNumpyArray of the same format , and can be done with +-*/%
numpyArray +  numpyArray= NewNumpyArray with the same rules with the arrays being of the same size.

numpy.dot(matrix1,matrix2)
Is used to perform the dot product.
Aggregation operations:
numpy.Sum(numpyArray)
Sums all the elements inside the numpy array, can specify axises to perform the operation on.

numpy.max(), numpy.mean, numpy.std (Standard deviation)
numpy.argmax(array,axis) Is used to find the location of the maximal value.
numpy.Concatenate , insert - Is used to append or insert values. Numpy array must be specified
numpy.split(numpyArray ,Sections, axis =0 ), divides  a specified numpyArray using the specified sectioning method with an specified axis.
numpy.sort() Sorts the array numpy. Unique returns the unique elements , without changing the format of the array