2.2 Variables, Objects and Expressions
43
In [1]: x = 2
In [2]: y = 4.0
In [3]: s = ’hello’
In [4]: type(x)
# ...object named x is an integer
Out[4]: int
In [5]: type(y)
# ...object named y is a float
Out[5]: float
In [6]: type(s)
# ...object named s is a string
Out[6]: str
Type Conversion Objects may be converted from one type to another if it makes
sense. If, e.g., x is the name of an int object, writing
In [1]: x = 1
In [2]: y = float(x)
In [3]: y
Out[3]: 1.0
shows that y then becomes a floating point representation of x. Similarly, writing
In [1]: x = 1.0
In [2]: y = int(x)
In [3]: y
Out[3]: 1
illustrates that y becomes an integer representation of x. Note that the int function
rounds down, e.g., y = int(1.9) also makes y become the integer 1. Type
conversion may also occur automatically.
2.2.5 Automatic Type Conversion
What if we add a float object to an int object? We could, e.g., write
In [1]: x = 2
In [2]: x = x + 4.0
In [3]: x
Out[3]: 6.0
What happens here, is that automatic type conversion takes place, and the new x
will have the value 6.0, i.e., refer to an object of type float.
43
In [1]: x = 2
In [2]: y = 4.0
In [3]: s = ’hello’
In [4]: type(x)
# ...object named x is an integer
Out[4]: int
In [5]: type(y)
# ...object named y is a float
Out[5]: float
In [6]: type(s)
# ...object named s is a string
Out[6]: str
Type Conversion Objects may be converted from one type to another if it makes
sense. If, e.g., x is the name of an int object, writing
In [1]: x = 1
In [2]: y = float(x)
In [3]: y
Out[3]: 1.0
shows that y then becomes a floating point representation of x. Similarly, writing
In [1]: x = 1.0
In [2]: y = int(x)
In [3]: y
Out[3]: 1
illustrates that y becomes an integer representation of x. Note that the int function
rounds down, e.g., y = int(1.9) also makes y become the integer 1. Type
conversion may also occur automatically.
2.2.5 Automatic Type Conversion
What if we add a float object to an int object? We could, e.g., write
In [1]: x = 2
In [2]: x = x + 4.0
In [3]: x
Out[3]: 6.0
What happens here, is that automatic type conversion takes place, and the new x
will have the value 6.0, i.e., refer to an object of type float.
