0% found this document useful (0 votes)
15 views53 pages

Python Introduction

Uploaded by

hajabdoulrazak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views53 pages

Python Introduction

Uploaded by

hajabdoulrazak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 53

— Simplicité du langage

— Syntaxe claire et cohérente


— Indentation significative
— Gestion automatique de la mémoire (garbage collector)
— Typage dynamique fort : pas de déclaration
Points forts de Python :
— langage de très haut niveau ;
— sa lisibilité ;
— « langage algorithmique exécutable ».
Chaine de compilation

Chaine d’interprétation
Technique de production de Python

Chaine de production de Python


Construction des programmes
• Implémentations de Python (Mise en œuvre)

• Modes d’exécution de Python


• Programs are composed of modules
• Modules contain statements
• Statements contain expressions
• Expressions create and process objects
>>> 'hello world!'
'hello world!'
•Python is an interpreted
language >>> 3 + 7
10
•The interpreter provides an
>>> 3 < 15
interactive environment to
True
play with the language
>>> 'print me'
•Results of expressions are 'print me'
printed on the screen >>> print( 'print me‘)
print me
>>>
The ‘#’ starts a line comment

>>> 'this will print'


'this will print'
>>> #'this will not'
>>>
• Are not declared, just assigned
• The variable is created the first time you assign it
a value
• Are references to objects
• Type information is with the object, not the
reference
• Everything in Python is an object
• Everything means
>>> x = 7
everything, including
>>> x
functions and classes 7
(more on this later!) >>> x = 'hello'
• Data type is a property >>> x
of the object and not of 'hello'
>>>
the variable
• Integer – the equivalent of
a C long >>> 132224
• Long Integer – an 132224
unbounded integer value. >>> 132323 ** 2
17509376329L
>>>
• int(x) converts x to an >>> 1.23232
integer 1.2323200000000001
>>> print (1.23232)
• float(x) converts x to a 1.23232
floating point >>> 1.3E7
• The interpreter shows 13000000.0
a lot of digits >>> int(2.0)
2
>>> float(2)
2.0
• Built into Python
• Same operations are >>> x = 3 + 2j
supported as integer and >>> y = -1j
>>> x + y
float
(3+1j)
>>> x * y
(2-3j)
• Strings are immutable
• There is no char type like >>> x = 'hello'
>>> x = x + ' there'
in C++ or Java
>>> x
• + is overloaded to do 'hello there'
concatenation
• Can use single or double quotes, and three double
quotes for a multi-line string
>>> 'I am a string'
'I am a string'
>>> "So am I!"
'So am I!'
>>> s = """And me too!
though I am much longer
than the others :)"""
'And me too!\nthough I am much longer\nthan the others :)‘
>>> print s
And me too!
though I am much longer
than the others :)‘
• len(String) – returns the
>>> s = '012345'
number of characters in the
>>> s[3]
String
'3'
>>> s[1:4]
• str(Object) – returns a
'123'
String representation of the
>>> s[2:]
Object
'2345'
>>> s[:4] >>> len(s)
'0123' 6
>>> s[-2] >>> str(10.3)
'4' '10.3'
• Ordered collection of data
• Data can be of different >>> x = [1,'hello', (3 + 2j)]
types >>> x
• Lists are mutable [1, 'hello', (3+2j)]
>>> x[2]
• Issues with shared references
(3+2j)
and mutability >>> x[0:2]
• Same subset operations as [1, 'hello']
Strings
• x[i] = a reassigns the >>> x = [1,2,3]
>>> y = x
ith element to the value a
>>> x[1] = 15
• Since x and y point to the >>> x
same list object, both are [1, 15, 3]
changed >>> y
[1, 15, 3]
• The method append also >>> x.append(12)
modifies the list >>> y
[1, 15, 3, 12]
>>> x = [1,2,3]
• The method append >>> y = x
modifies the list and >>> z = x.append(12)
returns None >>> z == None
True
• List addition (+) >>> y
returns a new list [1, 2, 3, 12]
>>> x = x + [9,10]
>>> x
[1, 2, 3, 12, 9, 10]
>>> y
[1, 2, 3, 12]
>>>
• Tuples are immutable
versions of lists
• One strange point is the >>> x = (1,2,3)
format to make a tuple with >>> x[1:]
(2, 3)
one element:
>>> y = (2,)
‘,’ is needed to differentiate >>> y
from the mathematical (2,)
expression (2) >>>
• A set of key-value pairs
• Dictionaries are mutable

>>> d = {1 : 'hello', 'two' : 42, 'blah' : [1,2,3]}


>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['blah']
[1, 2, 3]
• Entries can be changed by assigning to that entry
>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['two'] = 99
>>> d
{1: 'hello', 'two': 99, 'blah': [1, 2, 3]}
• Assigning to a key that does not exist adds an entry
>>> d[7] = 'new entry'
>>> d
{1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]}
• The del method deletes an element from a dictionary

>>> d
{1: 'hello', 2: 'there', 10: 'world'}
>>> del(d[2])
>>> d
{1: 'hello', 10: 'world'}
• The built-in list >>> l1 = [1] >>> d = {1 : 10}
function will copy >>> l2 = list(l1) >>> d2 = d.copy()
a list >>> l1[0] = 22 >>> d[1] = 22
>>> l1 >>> d
• The dictionary has [22] {1: 22}
a method called >>> l2 >>> d2
copy [1] {1: 10}
• Lists, Tuples, and Dictionaries can store any type
(including other lists, tuples, and dictionaries!)
• Only lists and dictionaries are mutable
• Integers: 2323, 3234L
• Floating Point: 32.3, 3.1E2
• Complex: 3 + 2j, 1j
• Lists: l = [ 1,2,3]
• Tuples: t = (1,2,3)
• Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}
• 0 and None are false
• Everything else is true
• True and False are aliases for 1 and 0
respectively
• Compound boolean expressions >>> True and False
short circuit False
• and and or return one of the >>> False or True
elements in the expression True
>>> 7 and 14
• Note that when None is returned 14
the interpreter does not print >>> None and 2
anything >>> None or 2
2
inflobj = open(‘data’, ‘r’) Open the file ‘data’ for input

S = inflobj.read() Read whole file into one


String
S = inflobj.read(N) Reads N bytes
(N >= 1)
L = inflobj.readlines() Returns a list of line strings
outflobj = open(‘data’, ‘w’) Open the file ‘data’
for writing
outflobj.write(S) Writes the string S to
file
outflobj.writelines(L) Writes each of the
strings in list L to file
outflobj.close() Closes the file
• The interpreter is a good place to try out some code,
but what you type is not reusable
• Python code files can be read into the interpreter
using the import statement
• In order to be able to find a module called myscripts.py,
the interpreter scans the list sys.path of directory names.
• The module must be in one of those directories.

>>> import sys


>>> sys.path
['C:\\Python26\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python26.zip',
'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win',
'C:\\Python26\\lib\\lib-tk', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages']
>>> import myscripts
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import myscripts.py
ImportError: No module named myscripts.py
• Python uses indentation instead of braces to determine
the scope of expressions
• All lines must be indented the same amount to be part
of the scope (or indented more if part of an inner
scope)
• This forces the programmer to use proper indentation
since the indenting is part of the program!
import math
x = 30
if x <= 15 : >>> import ifstatement
y = x + 15 y = 0.999911860107
elif x <= 30 : >>>
y = x + 30 In interpreter
else :
y=x
print ‘y = ‘,
print math.sin(y)

In file ifstatement.py
>>> import whileloop
x=1 1
while x < 10 : 2
print x 3
x=x+1 4
5
6
In whileloop.py
7
8
9
>>>
In interpreter
for x in [1,7,13,2] : for x in range(5) :
forloop1.py forloop2.py print (x)
print (x)

~: python forloop1.py ~: python forloop2.py


1 0
7 1
13 2
2 3
4

range(N) generates a list of numbers [0,1, …, n-1]


def max(x,y) : >>> import functionbasics
if x > y : >>> max(3,5)
return x 5
else : >>> max('hello', 'there')
return y 'there'
>>> max(3, 'hello')
'hello'
functionbasics.py
• Can be assigned to a variable
• Can be passed as a parameter
• Can be returned from a function
• Functions are treated like any other variable in
Python, the def statement simply assigns a function
to a variable
>>> x = 10
>>> x
10
• Functions are objects >>> def x () :
• The same reference ... print 'hello'
rules hold for them as >>> x
for other objects <function x at 0x619f0>
>>> x()
hello
>>> x = 'blah'
>>> x
'blah'
• Parameters can be
>>> def foo(x = 3) :
assigned default values ... print x
• They are overridden if ...
a parameter is given >>> foo()
for them 3
>>> foo(10)
• The type of the default 10
doesn’t limit the type of >>> foo('hello')
a parameter hello
• Call by name >>> def foo (a,b,c) :
• Any positional ... print a, b, c
arguments must ...
come before >>> foo(c = 10, a = 2, b = 14)
2 14 10
named ones in a
>>> foo(3, c = 2, b = 19)
call 3 19 2
• A lambda expression >>> f = lambda x,y : x + y
returns a function >>> f(2,3)
object 5
• The body can only >>> lst = ['one', lambda x : x * x, 3]
>>> lst[1](4)
be a simple
16
expression, not
complex statements
import mymodule Brings all elements
of mymodule in, but
must refer to as
mymodule.<elem>
from mymodule import x Imports x from
mymodule right into
this namespace
from mymodule import * Imports all elements
of mymodule into
this namespace
• https://www.python.org/
• https://perso.limsi.fr/pointal/_media/python:cours:courspython
3.pdf
Ecrire des scripts réalisant les fonctions suivantes
1. Le calcul du logarithme de 2 par la sommation d'une série
infinie :

2. Une boucle qui calcule et affiche la somme de nombres


impairs.
3. Étant données trois variables : a, b et c, considérées comme
des coefficients d'une équation quadratique : a⋅x2+b⋅x+c=0,
écrire un programme qui trouve et imprime la ou les solutions
x de cette équation, éventuellement affiche le message
diagnostique, notifiant l'absence de solution.
4. Lire un nombre flottant comme une chaîne avec le point
décimal, trouver le point, séparer les parties avant et après.
Ecrire des scripts réalisant les fonctions suivantes
(programme linéaire puis par appel de fonction)
1. Suite de Fibonacci jusqu’à n
2. Calcul du factorielle n
3. Calcul des zéros d’une fonction par la méthode
dichotomique

You might also like