int
¶my_int = 6
print(f"value: {my_int}, type: {type(my_int)}")
float
¶my_float = float(my_int)
print(f"value: {my_float}, type: {type(my_float)}")
Note that division of int
s produces float
:
print(1 / 1)
print(6 / 5)
Be aware of the binary floating-point pitfalls (see Decimal for workaround):
val = 0.1 + 0.1 + 0.1
print(val == 0.3)
print(val)
//
, modulus %
, power **
¶7 // 5
7 % 5
2**3
from decimal import Decimal
from_float = Decimal(0.1)
from_str = Decimal("0.1")
print(f"from float: {from_float}\nfrom string: {from_str}")
my_decimal = Decimal("0.1")
sum_of_decimals = my_decimal + my_decimal + my_decimal
print(sum_of_decimals == Decimal("0.3"))
Mathematical operator precedence applies. Use brackets if you want to change the execution order:
print(1 + 2**2 * 3 / 6) # 1 + 4 * 3 / 6 == 1 + 12 / 6 == 1 + 2
print((1 + 2**2) * 3 / 6)