Variables, Types and Operations

First lesson of the Python Fundamentals course, free to read: about 15 minutes, 3 exercises and 3 quiz questions. This is the catalogue's base lesson; in the student space, it is rewritten for your profile.

Objectives

  • Create variables and assign values to them
  • Recognize the int, float, str and bool types with type()
  • Convert a value from one type to another and display it with an f-string

VariablesBasic typesf-strings

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.

  1. CodeDifficulty 1Python in the browser2 hints

    Compute a total including tax

    The variables prix_ht and quantite_txt are provided. quantite_txt is a string.

    1. Convert quantite_txt to an integer in a variable quantite.
    2. Compute total_ttc = prix_ht × quantite × 1.2, rounded to 2 decimal places with round().
    3. Create a string message of 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)
  2. CodeDifficulty 2Python in the browser2 hints

    Floor division and remainder

    A warehouse receives nb_articles items that it packs into boxes of capacite items.

    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 if nb_articles is even.
    nb_articles = 257
    capacite = 12
    
    cartons_pleins = ...
    reste = ...
    est_pair = ...
  3. Multiple choiceDifficulty 11 hint

    Type of a division

    What is the type of the result of 10 / 2 in Python?

    • int
    • float
    • str
    • bool

End-of-lesson quiz

  1. What is "5" + "5"?

    • 10
    • "55"
    • An error
  2. Which statement prints Prix : 3.50 for p = 3.5?

    • print("Prix : {p:.2f}")
    • print(f"Prix : {p:.2f}")
    • print(f"Prix : p:.2f")
  3. What is 17 % 5?

    • 3
    • 3.4
    • 2

The rest of the course

  1. Conditions: if, elif, else15 min
  2. Lists and Loops20 min
  3. Dictionaries, Tuples and Sets20 min
  4. Functions and Error Handling20 min

Python Fundamentals · Beginner · 2 h 30 min