Python Language Tour
We will take a tour of the Python language without necessarily covering everything as it is very rich in features.
Warning
As the Python language frequently evolves and brings improvements and simplifications, the code examples seen here may be different from what you find in the literature.
Getting Started
- Open VSCode in an empty folder
- Create a file hello.py containing
print("Hello")
- Run the command
python hello.py
- Some code to get an idea of the language
# This is a comment
a = 10
print(a)
a = "hello"
print(a)
print("The value of a is", a)
a = "22"
b = 10
# erreur car python est fortement typé et n'autorise pas l'addition sur deux types différents
# c = a + b
# print("a + b", c)
print(a + str(b), int(a) + b)
if b == 10:
print(b)
print(b)
else:
print("b différent de 10 / b is not 10")
def add(x, y):
print(f"addition of {x} and {y}")
return x + y
# A function can be documented with optional type hints and a docstring
def multiply(x: int, y: int) -> int:
"""
Multiply x and y
Parameters:
x: first number
y: second number
Returns:
the result of the multiplication
"""
return x * y
print(add(-810, b))
f = add
print(f(-810, b))
print("range demo: générateur / generator")
r = range(10)
print(r)
print("Start value", r.start, "pas / step", r.step)
print("range loop")
for item in r:
print(item)
for item in range(10):
print(item)
for i in range(10, 21, 3):
print(i)
message = "I ♥️ Python"
for letter in message:
print(letter)
for i in range(len(message)):
print(i, message[i])
Some Features
- Python is dynamically typed: a variable can change its type during its usage (opposite of statically typed)
- Python is strongly typed: each data has a type and does not change implicitly
- Python supports object-oriented and functional programming
- Indentation is used to define code blocks (instead of
{}
braces commonly found in other languages)- The indentation size should be consistent within the same block
- It is recommended to have an indentation of 4 spaces
- There are several programming conventions, but they have many common points. The official convention is called pep 8. Here are some rules and recommendations:
- Snake case for functions. Ex.
find_student()
- Use spaces for indentation and avoid using the tab key
- Snake case for functions. Ex.
Basic Types and Operations
- Integer (int), float, and complex numbers
- Strings
- Boolean values and boolean operators
and
,or
, andnot
- Comparison operators
>
,<
, ... that return a booleanis
allows testing the identity between two objects. Its result can be customized.==
is sometimes equivalent tois
- As Python is strongly typed, converting a value to another type must be done explicitly using
int()
,float()
,complex()
,str()
, ...
# https://www.w3schools.com/python/python_operators.asp
x = 15
print("puissance", x**10, "partie entière de la division", x // 4)
# * a plus de priorité par rapport à +
print(1 + 2 * 3)
print(10 < x and x < 20, "est equivalent à", 10 < x < 20)
c = ((i, j) for i in (True, False) for j in (True, False))
for i, j in c:
print(i, "and", j, i and j)
print(i, "or", j, i or j)
print("not", i, not j)
print(10 in range(50))
print(10 in range(0, 50, 3))
print(10 not in [1, 2, 10, 33])
# && -> and (attention & a un comportement différent)
Exceptions
def f_that_throws(b):
if b:
return "Success"
else:
raise Exception()
print(f_that_throws(True))
# Crash si on n'attrape pas l'exception
# print(f_that_throws(False))
try:
print(f_that_throws(True))
print("Before")
f_that_throws(False)
print("After")
except Exception:
print("Oups")
Standard Collections
- Collection: a type (or structure) of data that allows managing a set of data
- Python offers several built-in collection types
- Here are the 4 most commonly used types: list, dict, set, and tuple
# List: éléments ordonnées. Chauqe élément est défini par sont indice
numbers = [3, 4, -3, "hello", True, 390]
numbers.append(10)
numbers.append(100)
numbers.remove(3)
print(numbers)
print(numbers[0], numbers[-1], numbers[-2])
print(numbers[0:3], numbers[:3], numbers[1:5])
print(numbers[-3:-1], numbers[2:])
for number in numbers:
print(number)
for i in range(len(numbers)):
print(i, numbers[i])
# Dictionnaires: élements identidifiés par une clé (on parle aussi de couples clé/valeur)
pokemon1 = {"name": "Pikachu", "hp": 10, "type": "Thunder", 5: "une valeur"}
print(
pokemon1,
pokemon1["name"],
pokemon1["type"],
pokemon1[5],
"name" in pokemon1,
"surname" in pokemon1,
)
for key, value in pokemon1.items():
print(key, value)
# Set (ensemble) : élements non ordonnées et uniques
messages = {"hello", "world", 2023}
print(messages, "hello" in messages, 2024 in messages)
messages.add(2023)
print(messages)
for message in messages:
print(message)
# Tuple : éléments ordonnées immutable (on ne peut ajouter ou supprimer d'éléments). On peut le considérer comme une liste immutable
n1 = (12, 34, 55, 33)
print(n1, n1[2:])
for item in n1:
print(item)
for i in range(len(n1)):
print(i, n1[i])
List, Dictionary, and Set Comprehension
- Allows creating a new list, dictionary, or set from an existing collection
- Allows replacing certain operations that would have been done with loops
- For a list
[f(index) for index in input_seq if condition]
(input_seq
is a list, tuple, or any iterable sequence with an index) - For a list
[f(item) for item in input_seq if condition]
(input_seq
is a list, tuple, or any iterable sequence) - For a dictionary
{f_key(item):f_value(item) for item in input_seq if condition}
(input_seq
is an iterable sequence) f, f_key, f_value
are arbitrary functions- The
if condition
part is optional - It is also possible to replace nested loops with a single comprehension
items = [0, 1, 2, 3, 4]
# Double de chaque élément
double_items_1 = []
for item in items:
double_items_1.append(item * 2)
print("double_items_1", double_items_1)
# Transformer (to map en Anglais) avec les compréhensions
results = [item * 2 for item in items]
print(results)
print([item * 2 for item in items])
# puissance 4 des entier entre -2 et 9 avec un pas de 2
print([item**4 for item in range(-2, 10, 2)])
# Filtrage
# Garder uniquement les éléments pairs
items = [9, 22, -2, 11, 1232, 2323]
print([item for item in items if item % 2 == 0])
# Equivalent avec un boucle for
results = []
for item in items:
if item % 2 == 0:
results.append(item)
print(results)
# Garder uniquement les éléments pairs et les multiplier par 3
print([item * 3 for item in items if item % 2 == 0])
messages = ["Hello", "J'aime", "Python"]
print([len(message) for message in messages])
print([f"{message}." for message in messages])
# Dict (dictionnaire)
print({message: len(message) for message in messages})
# Set ensemble
print({len(message) for message in messages})
# Card game from ranks and symbols
ranks = range(1, 11)
symbols = ["💗", "♠️", "🍀", "🔶"]
# Produit cartésien
print([f"{r}{s}" for r in ranks for s in symbols])
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([item for row in m for item in row])
row_count = range(len(m))
print([f"m[{i}, {j}] => {m[i][j]}" for i in row_count for j in range(len(m[i]))])
# Equivalent en for
result = []
for i in row_count:
for j in range(len(m[i])):
result.append(f"m[{i}, {j}] => {m[i][j]}")
print("Tranformation matrice vers liste avec for", result)
# Pour faire une compréhension de tuple, il faut utiliser tuple()
print(tuple(x + 6 for x in range(10)))
Using a Third-Party Library
- Even though Python's standard library is rich, we often need to use third-party libraries to speed up development
- The standard repository for Python libraries is PyPI (Python Package Index)
- We can use its search engine to find a library. For example, let's search for the matplotlib library
- Once on the library's page, we can find the command to install it locally. For matplotlib, the command will be
pip install matplotlib
(if pip is not found, try withpython -m pip install matplotlib
) - Then, we can use the library by referring to its documentation. For example, matplotlib offers tutorials which is a good starting point.