Type Conversions
What if an expression involves variables of various types? For numeric types, Python attempts to convert the type(s) of the variable(s) in a sensible way so that the expression can be evaluated. Generally, a mixture of floats and ints produces a result of type float:
Here, the value of x is 5.0, a float, so Python converts y to a float, and resolves the expressions x+y
and x/y
using floating-point arithmetic, giving a float result. The return type of an arithmetic expression depends on both the operator and the types of the operands. Consider what happens if we are operating on two ints:
Addition is closed under the integers (adding two integers produces an integer), so the expession xi+yi
results in an int. But division is not closed under the integers, so xi/yi
produces a float. If you want to do integer division with two ints (that is, get an integer quotient and a integer remainder), you can use the floor division //
and modulo %
operators, respectively (as in, "5 / 3 equals 1 remainder 2"):
Note: Python 2.x defined a different type of division for integers, which is equivalent to what is now floor division in Python 3.x. If you are using Python 2.x, you will want to be cautious about your division operations. Alternatively, you can include the statement from __future__ import division
at the top of your code modules. But you're really better off migrating to Python 3.
Here are more examples of converting quantities to different types in Python using various built-in functions:
The two last expressions show that bool()
of a nonzero number is True
, and True
has the same value as the integer 1. (False
has the same value as the integer 0.)
Try typing (as well as examining the type of) a few expressions of your own with the Python interpreter. If you have programmed in any other language, this should feel simple and familiar.