Choosing a name¶
Variables store a value in memory to re-use a result later without redoing the calculation. It also simplifies the understanding of the code.
In Python a variable is a word with as a letter all the alphanumeric characters as well as the _
but it can not start with a number.
* yes: PiaNo piano P_ i _a_ n _O
* no: 666 666piano
By convention we use _ for a variable with several words: my _age
, average_ notes
Assignment¶
Assigning a value to a variable is done with the = sign
age = 42
print(age)
42
Comparison¶
Note that the comparison uses the ==
sign (see Course on Tests)
Modification¶
I can modify my variable:
age = 45
print(age)
age = age + 1
print(age)
45 46
The assignment is not an equality in the mathematical sense otherwise age = age + 1
would not make much sense. This line indicates that the variable age will receive the value of the variable plus one.
The incrementation of a variable is so usual that we defined the operator + =
for that:
age += 1
print(age)
age += 3
print(age)
47 50
print(age == 42)
print(age == 41)
False False
There are also the * = / =
and - =
operators
Exercise¶
Convert the temperature 100 degrees Fahrenheit to Celcius knowing that celcius = 5/9 * (fahrenheit - 32)
and display the result.
ma_temp_f = 100
Of course operators / and * have priority over + and -. At equal level, the operations are from left to right.
{{ PreviousNext("00 - Premiers calculs.ipynb", "02 - Les types.ipynb") }}