int

In [1]:
my_int = 6
print('value: {}, type: {}'.format(my_int, type(my_int)))
value: 6, type: <class 'int'>

float

In [2]:
my_float = float(my_int)
print('value: {}, type: {}'.format(my_float, type(my_float)))
value: 6.0, type: <class 'float'>

Note that division of ints produces float:

In [3]:
print(1 / 1)
print(6 / 5)
1.0
1.2

Be aware of the binary floating-point pitfalls (see Decimal for workaround):

In [4]:
val = 0.1 + 0.1 + 0.1
print(val == 0.3)
print(val)
False
0.30000000000000004

Floor division //, modulus %, power **

In [5]:
7 // 5
Out[5]:
1
In [6]:
7 % 5
Out[6]:
2
In [7]:
2 ** 3
Out[7]:
8
In [8]:
from decimal import Decimal
In [9]:
from_float = Decimal(0.1)
from_str = Decimal('0.1')
print('from float: {}\nfrom string: {}'.format(from_float, from_str))
from float: 0.1000000000000000055511151231257827021181583404541015625
from string: 0.1
In [10]:
my_decimal = Decimal('0.1')
sum_of_decimals = my_decimal + my_decimal + my_decimal
print(sum_of_decimals == Decimal('0.3'))
True

Operator precedence in calculations

Mathematical operator precedence applies. Use brackets if you want to change the execution order:

In [11]:
print(1 + 2**2 * 3 / 6) # 1 + 4 * 3 / 6 == 1 + 12 / 6 == 1 + 2
print((1 + 2**2) * 3 / 6)
3.0
2.5