42
2 A Few More Steps
2.2.3 Assignment
We have learned previously that, for example, x = 2 is an assignment statement.
Also, when discussing ball.py in Sect. 1.2, we learned that writing, e.g., x = x +
4 causes the value of x to be increased by 4. Alternatively, this update could have
been achieved (slightly faster) with x += 4. In a similar way, x -= 4 reduces the
value of x by 4, x *= 4 multiplies x by 4, and x /= 4 divides x by 4, updating the
value of x accordingly.
The following also works as expected (but there is one point to make):
In [1]: x = 2
In [2]: y = x
# y gets the value 2
In [3]: y = y + 1
# y gets the value 3
In [4]: x
# x value not changed
Out[4]: 2
Observe that, after the assignment y = x, a change in y did not change the value of
x (also, if rather x had been changed, y would have stayed unchanged). We would
observe the same had x been the name of a float or a string, as you will realize
if you try this yourself. 3 This probably seems obvious, but it is not the case for all
kinds of objects. 4
2.2.4 Object Type and Type Conversion
The Type of an Object By now, we know that an assignment like x = 2 triggers
the creation of an object by the name x. That object will be of type int and have
the value 2. Similarly, the assignment y = 2.0 will generate an object named y,
with value 2.0 and type float, since real numbers like 2.0 are called floating point
numbers in computer language (by the way, note that floats in Python are often
written with just a trailing “dot”, e.g., 2. in stead of 2.0). We have also learned
that when Python interprets, e.g., s = ‘This is a string’, it stores the text (in
between the quotes) in an object of type str named s. These object types, i.e., int,
float and str, are still just a few of the many built-in object types in Python. 5
The Type Function There is a useful built-in function type that can be used to
check the type of an object:
3 To test the string, you may try (in the order given): x = ‘yes’; y = x; y = y + ‘no’, and
then give the commands y and x to confirm that y has become yesno and x is still yes.
4 In Python, there is an important distinction between mutable and immutable objects. Mutable
objects can be changed after they have been created, whereas immutable objects can not. Here,
the integer referred to by x is an immutable object, which is why the change in y does not change
x. Among immutable objects we find integers, floats, strings and more, whereas arrays and lists
(Sect. 5.1) are examples of mutable objects.
5 https://docs.python.org/3/library/stdtypes.html.
Précédent

- 64/350

Suivant