Pulsars
0 %
Log inSign up

Variables and basic types

The concept of a variable

The concept of a variable

A variable is a named space in memory that lets you store a value to reuse later in the program. It's a bit like a labeled box: you put something in it, and you can then retrieve or replace its contents using its label (its name).

In Python, creating a variable is done through assignment, using the = symbol:

age = 14

This line creates a variable named age and assigns it the value 14. Careful: this = does not mean equals as in mathematics; it means that the variable takes the value of what is on the right. This line reads: age takes the value 14.

You can then reuse this variable, for example to display it or perform a calculation:

age = 14
print(age)
age = age + 1
print(age)

This program displays 14 then 15. The line age = age + 1 first computes age + 1 (so 15), then stores this result in the variable age, which replaces its old value. The old value (14) is lost: a variable can only hold one value at a time.

To ask the user for a value while the program is running, we use the input function:

prenom = input("What is your name? ")
print("Hello", prenom)

The program first displays the question, waits for the user to type an answer on the keyboard and press Enter, then stores this answer in the variable prenom.

The name of a variable should be chosen carefully: clear, without spaces, and representative of what it contains (age rather than x, for example).