Variables, types and operations
In Python, a variable is simply a label attached to a value. You create it by writing its name, the = sign, then the value. There is no need to declare the type in advance: Python infers it on its own.
prenom = "Awa" # a string (str)
age = 29 # an integer (int)
taille = 1.68 # a decimal number (float)
est_inscrite = True # a boolean (bool): True or False
print(prenom, age) # prints: Awa 29
print(type(taille)) # prints: <class 'float'>
Choose explicit lowercase names with underscores (prix_unitaire rather than pu). A name never starts with a digit and contains no spaces.
Arithmetic operators
a, b = 17, 5
print(a + b) # 22 addition
print(a - b) # 12 subtraction
print(a * b) # 85 multiplication
print(a / b) # 3.4 true division: the result is always a float
print(a // b) # 3 floor division (quotient)
print(a % b) # 2 remainder of the division (modulo)
print(a ** 2) # 289 power
The modulo % is very useful: n % 2 == 0 means “n is even”. Also be careful with decimal numbers: 0.1 + 0.2 gives 0.30000000000000004, because floats are stored in binary. To display an amount, round with round(value, 2) or use a display format.
Converting types
Data coming from outside (input with input(), a text file, a form) is almost always strings. Adding two strings sticks them end to end instead of adding them:
quantite = "3"
print(quantite + "2") # "32": text concatenation
print(int(quantite) + 2) # 5 : conversion to an integer, then addition
print(float("19.90") * 2) # 39.8
print(str(42) + " years") # "42 years"
If the conversion is impossible (int("abc")), Python raises a ValueError. We will see later how to handle it.
f-strings for clean output
An f-string is a string preceded by f. Everything between curly braces is evaluated and then inserted:
produit = "clavier"
prix = 49.9
quantite = 3
total = prix * quantite
print(f"{quantite} x {produit} = {total:.2f} €")
# 3 x clavier = 149.70 €
The :.2f format forces two decimal places. You can also write {total:,.2f} for a thousands separator, or {taux:.1%} to display a percentage.
Key takeaways
=assigns a value,==compares two values.type()reveals the type of a value.- Always convert text to numbers before calculating.
- f-strings are the modern, readable way to build text.
Exercises
Solutions and tests stay on the server. In the student space, your code is run and checked, and the tutor gives hints before the solution.
Compute a total including tax
The variables
prix_htandquantite_txtare provided.quantite_txtis a string.- Convert
quantite_txtto an integer in a variablequantite. - Compute
total_ttc= prix_ht × quantite × 1.2, rounded to 2 decimal places withround(). - Create a string
messageof the form"Total : 59.88 €"with an f-string (2 decimal places).
prix_ht = 24.95 quantite_txt = "2" # 1. Conversion quantite = ... # 2. Calcul total_ttc = ... # 3. Message message = ... print(message)- Convert
Floor division and remainder
A warehouse receives
nb_articlesitems that it packs into boxes ofcapaciteitems.Compute:
cartons_pleins: the number of completely filled boxes;reste: the number of items left over outside a box;est_pair: a boolean that is True ifnb_articlesis even.
nb_articles = 257 capacite = 12 cartons_pleins = ... reste = ... est_pair = ...Type of a division
What is the type of the result of
10 / 2in Python?- int
- float
- str
- bool
End-of-lesson quiz
What is
"5" + "5"?- 10
- "55"
- An error
Which statement prints
Prix : 3.50forp = 3.5?- print("Prix : {p:.2f}")
- print(f"Prix : {p:.2f}")
- print(f"Prix : p:.2f")
What is
17 % 5?- 3
- 3.4
- 2
The rest of the course
- Conditions: if, elif, else15 min
- Lists and Loops20 min
- Dictionaries, Tuples and Sets20 min
- Functions and Error Handling20 min