Pulsars
0 %
Log inSign up

Variables and basic types

Basic types: int, float, str, bool

Basic types

Every value handled in Python has a type, which determines what you can do with it. Here are the four basic types you will encounter all the time:

  • int (whole number): 5, -3, 1000
  • float (decimal number): 3.14, -0.5, 2.0
  • str (string, text): "Hello", "14", "a"
  • bool (boolean, true or false): True or False
age = 14            # (a whole number, so of type int)
taille = 1.62        # (a decimal number, so of type float)
prenom = "Sam"        # (a string, so of type str)
est_majeur = False    # (a boolean, so of type bool)

You can check the type of a variable with the type function:

print(type(age))

This will display <class 'int'>.

A classic trap for beginners: "14" (with quotes) is a string, not a number! You cannot directly perform a calculation with it:

a = "14"
b = 2
print(a + b)  # (causes an error: you cannot add text and a number)

This is particularly important to know because the input function always returns a string, even if the user types a number. To turn this string into a number usable in a calculation, we use int(...) or float(...):

age_texte = input("How old are you? ")
age = int(age_texte)
print(age + 1)

Here, int(age_texte) converts the text typed by the user into a real integer, which then allows the calculation age + 1 to be performed without error.