1.2 A Python Program with Variables
7
guess) what is meant with the code. In simple cases, comments are probably not
much needed, but will soon be justified as the level of complexity steps up.
The next line read by Python is
v0 = 5 # Initial velocity
In Python, a statement like v0 = 5 is known as an assignment statement.
After this assignment, any appearance of v0 in the code will “represent” the initial
velocity, being 5 ms −1 in this case. This means that, whenever Python reads v0,
it will replace v0 by the integer value 5. One simple way to think of this, might
be as follows. With the assignment v0 = 5, Python generates a “box” in computer
memory with the name v0 written on top. The number 5 is then put into that box.
Whenever Python later meets the name v0 in the code, it finds the box, opens it,
takes out the number (here 5) and replaces the name v0 with the number.
The next two lines
g = 9.81 # Acceleration of gravity
t = 0.6
# Time
are also assignment statements, giving two more “boxes” in computer memory. The
box named g will contain the value 9.81, while the box named t contains 0.6.
Similarly, when Python later reads g and t in the code, it plugs in the numerical
values found in the corresponding boxes.
The assignments in a bit more detail
When Python interprets the assignment statement v0 = 5, the integer 5
becomes an object of type int and the variable name on the left-hand side
becomes a named reference for that object. Similarly, when interpreting the
assignment statements g = 9.81 and t = 0.6, g and t become named
references to objects created for the real numbers given. However, since we
have real numbers, these objects will be of type float (in computer language,
a real number is called a “floating point number”).
Now, with these assignments in place, Python knows of three variables (v0, g, t)
and their values. These variables are then used by Python when it reads the next
line, the actual “formula”,
y = v0*t - 0.5*g*t**2
# Vertical position
Again, according to its rules, Python interprets * as multiplication, − as minus and
** as exponentiation (let us also add here that, not surprisingly, + and / would
have been understood as addition and division, if such signs had been present in the
expression). Having read the line, Python performs the mathematics on the righthand side, and then assigns the result (in this case the number 1.2342) to the variable
name y.
Finally, Python reads
print(y)
Précédent

- 29/350

Suivant