Python is the most popular language, Python grew the most in the last 5 years (13.2%)
String string = "Hello, world!";
string = "Hello, world!"
String result = "Hello, world!" + 2;
result = "Hello, world!" + str(2)
Toute valeur est un objet
int
et float
str
''
et ""
pour les délimiter.bool
True
et False
str(2)
équivaut à "2"
équivaut à '2'
None
est l'équivalent de null
en Java._
nom_de_variable
_
indiquent qu'elles sont privées.word = "Python"
*
, concatené avec +
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
word[2]
vaut 't'
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
squares = [1, 4, 9, 16, 25]
coordinates = (4.2, 3.6)
x, y = coordinates
odd_numbers = {1, 3, 5, 7, 9}
capitals = {'Belgium': 'Brussels', 'France': 'Paris', 'Canada': 'Ottawa'}
2 in odd_numbers
équivaut à False
capitals['Canada']
équivaut à 'Ottawa'
'France' in capitals
équivaut à True
Sont considéré comme faux:
None
__bool__
ou __len__
si elle renvoie 0
ou False
Toute autre valeur est considérée comme vraie.
and
, or
et not
<
, <=
, >
, >=
, ==
, !=
, is
et is not
Python n'utilise pas d'accolades pour grouper des blocs d'instructions ensemble. L'indentation est sémantique.
if (x <= y)
x++;
y--;
z++;
if x <= y:
x += 1
y -= 1
z += 1
Cela évite des erreurs et apporte beaucoup plus de clarté.
if True:
pass
elif False:
pass
else:
pass
while i > 0:
pass
for i in range(10): pass
for i in squares: pass
for key in capitals: pass
for key, value in capitals.items(): pass
def fib(n, a=0, b=1):
"""Print a Fibonacci series up to n."""
while a < n:
print(a)
a, b = b, a+b
print()
fib(10) # equiv fib(n=10)
def cheeseshop(kind, *arguments, **keywords): print("-- Do you have any", kind, "?") print("-- I'm sorry, we're all out of", kind) for arg in arguments: print(arg) print("-" * 40) for kw in keywords: print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper="Michael Palin", client="John Cleese", sketch="Cheese Shop Sketch")
-- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- shopkeeper : Michael Palin client : John Cleese sketch : Cheese Shop Sketch
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def dist_to_origin(self):
return sqrt(self.x ** 2 + self.y ** 2)
point = Coordinate(1, 2)
point.x = 4
print(point.dist_to_origin())
Un module est un fichier python importable depuis d'autres modules.
import math
math.sqrt(4)
from math import sqrt
sqrt(4)
from math import sqrt as sq
sq(4)
Un fichier __init__.py
permet a Python de considérer son dossier parent comme un module.
Lorsqu'un module est importé, tout son contexte global est exécuté.
if __name__ == "__main__":
# execute only if run as a script
main()
try:
raise ValueError('Oops')
except ValueError as e:
print('An exception flew by!')
raise