Variables and Assignments

Variables and Assignments#

In the sheet on values and types, we performed calculations and observed the

results (type, value). To write programs, we will need to **memorize

intermediate results in variables** to reuse their values.

Exercise

  1. Using an expression as in the previous sheet, calculate the énergie cinétique (kinetic energy) \(\frac12 m v^2\) of an object of mass \(14,5\) kg travelling at \(100\) m/s:

### BEGIN SOLUTION
1. / 2 * 14.5 * 100**2
### END SOLUTION
72500.0

Exercise (continued)

  1. Similarly, calculate the kinetic energy of the same object moving at \(10\) m/s:

### BEGIN SOLUTION
1. / 2 * 14.5 * 10**2
### END SOLUTION
725.0

Exercise (continued)

  1. or at \(1000\) m/s:

### BEGIN SOLUTION
1. / 2 * 14.5 * 1000 * 1000 
### END SOLUTION
7250000.0

Exercise (continued)

  1. What is not satisfactory about this approach?

Variables#

When programming, it is often necessary to memorize a value in order to

be able to reuse it later: a number, a username, airline tickets

still available, the day of the week, an inventory, etc. To do this, we can give it

a name using a variable.

For example, in the following cell, we use two variables v and m to

name the value of the mass and velocity of the object, and then we use these names

to calculate its kinetic energy:

m = 14.5
v = 1000

1. / 2 * m * v**2
7250000.0

Reuse the previous cell to calculate the kinetic energy depending on whether the object’s velocity

is \(1\), \(10\), \(100\), or \(1000\) m/s.

Note

With variables, it was not only no longer necessary to write the same value

several times, but the expression gains in readability by using notations close

to the physics formula.

Definition: Variables

A variable (variable) in Python consists of two elements: its name or

identificateur (identifier) and its current value. It can be thought of as a

label that can be attached to a value using an affectation.

Definition: Assignment

Syntax

identificateur = expression

Semantics

  1. Calculates (or evaluates) the value of the expression.

  2. Attaches this value to the variable whose name is given by the identifier.

  3. Then stores the value in memory as long as the variable exists and has not been reassigned.

Example

After the assignment a = 1, the value 1 has a label a:

la valeur `1` avec une étiquette `a`

When reassigning a = 3 - 1, first a new value 2 is

created:

la valeur `1` avec une étiquette `a`
la valeur `2` sans étiquette

then the label a is attached to this new value:

la valeur `1` sans étiquette
la valeur `2` avec une étiquette `a`

Note that the original value 1 no longer has the label a, and is therefore no longer accessible

from this label.

The assignment b = a will then have the effect of attaching a new label to the value

2:

la valeur `2` avec deux étiquettes `a` et `b`

See also

Reference The label metaphor and images above are taken from

Code like a Pythonista: Idiomatic Python

by David Goodger.

The first assignment to a variable is also called its initialisation (initialisation).

As long as a variable has not been initialized, it cannot be used because it

does not exist. Thus, if we execute the following cell, an error is triggered

indicating that the variable c is not defined:

c
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[5], line 1
----> 1 c

NameError: name 'c' is not defined

Example

Assign the value 3 to the variable a.

a = 3

We can now reuse this value, alone or in any expression:

a
3
a + 1 
4
a + a + a
9

We can also modify the value of a:

a = 5
a
5
a = a + 1 
a
6
  • What happens if we execute the last cell again? What if we execute the last two cells alternately?

Note on Jupyter

The order in which you execute the cells is important, the variable contains the last value you assigned to it. The order of execution of the cells is indicated in brackets in the left margin.

Exercise

The following cell declares the variables pi and r. Use them to calculate the area and the perimeter of a disk with radius r for the different values given below. To simplify, you can consider that the variable pi contains the exact value of the well-known number. Use the empty cells to do your calculations. Don’t forget to also execute the cells that change the value of r.

pi = 3.1415
r = 5

Air:

### BEGIN SOLUTION
pi * r * r
### END SOLUTION
78.53750000000001

Perimeter:

### BEGIN SOLUTION
2 * pi * r
### END SOLUTION
31.415000000000003
r = 2.5

Air:

### BEGIN SOLUTION
pi * r * r
### END SOLUTION
19.634375000000002

Perimeter:

### BEGIN SOLUTION
2 * pi * r
### END SOLUTION
15.707500000000001
r = 10

Air:

### BEGIN SOLUTION
pi * r * r
### END SOLUTION
314.15000000000003

Perimeter:

### BEGIN SOLUTION
2 * pi * r
### END SOLUTION
62.830000000000005

Exercise (continued)

The following cell begins by defining two variables b and c. Complete the cell with a program that swaps the values of b and c. This program should only use assignments and, if useful, one or more new variables. It should not directly use the values \(5\) and \(8\).

# Ne pas changer les deux lignes suivantes
b = 5
c = 8

### BEGIN SOLUTION
temp = b
b = c
c = temp
### END SOLUTION
b   # doit afficher 8 (ancienne valeur de c)
8
c   # doit afficher 5 (ancienne valeur de b)
5
### BEGIN HIDDEN TESTS
assert( b == 8 )
assert( c == 5 )
### END HIDDEN TESTS

Hint

Aside: Comments in Python In Python, the symbol # (hash) marks the beginning of a commentaire (comment). This character

and everything else on the line containing it is ignored when the

program is executed. For example, in the previous cell, the text

# doit afficher 5 (ancienne valeur de b) will not be taken into account in the execution of the

program.

Comments are notes from the programmer that provide additional

information for the reader.

Some practical shortcuts

Syntax

Semantics

Equivalent syntax

x += a

Increment x by a

x = x + a

x -= a

Decrement x by a

x = x - a

x *= a

Multiply x by a

x = x * a

x /= a

Divide x by a

x = x / a

Conclusion#

In this sheet, we have introduced the notion of variable to memorize values in order to reuse them later, as well as to improve the readability of programs. We still need to point out two points of attention. On the one hand, one should not confuse assignment and equality, which have similar syntaxes, but very different semantics.

Attention

Assignment and equality: two different concepts

  • The assignment x = 5 is an instruction modifying the state of the memory.

  • The equality test x == 5 is a boolean expression (true or false value) whose value is “x is equal to 5?”. In other words: is the value contained in the variable x equal to 5?

On the other hand, if you have already programmed in languages other than Python, the semantics of the variables may have been different.