Python: Data Types - Bools and Bytes
ArithmeticPermalink
Python fully supports arithmetic between ints
and floats
. It will convert narrower numbers to match their less narrow counterparts when used with the binary arithmetic operators +, -, *, /, //, %
. When division with /, //
returns the quotient and %
returns the remainder.
Python considers ints
narrower than floats
. So, using a float in an expression ensures the result will be a float too. However, when doing division, the result will always be a float, even if only integers are used.
>>> 3 - 2.0
1.0
# Division always returns a float.
>>> 6 / 2
3.0
# If an int result is needed, you can use `//` to truncate the result.
>>> 7 // 4
1
ConvertionPermalink
To convert a float to an integer, you can use int()
. Also, to convert an integer to a float, you can use float()
.
>>> int(6 / 2)
3
>>> float(1 + 2)
3.0
Leave a Comment