Python Numbers

In Python there are three types of numbers:

  • Integer: Integer (or int) number type indicates a whole number.
  • Float: If the number has a decimal portion, it is a floating-point number (or float).
  • Complex: Complex numbers have real and imaginary parts.
x = 5               # Integer
y = 3.14            # Float
z = 2 + 3j          # Complex Number

Number Type Conversion

To convert from one number type to another, you can use int(), float(), or complex() functions.

x = 5
y = 3.14
z = 2 + 3j

t = float(x)       # converting from int(x) to float (t = 5.0)
w = int(y)         # converting from float(y) to int (w = 3)
u = complex(x)     # converting from int(x) to complex

Arithmetic Operators

You can use the following arithmetic operators in numbers:

OperatorDescriptionFormatExample
+Additiona + b3 + 5 = 8
Subtractiona – b10 – 7 = 3
*Multiplicationa * b3 * 4 = 12
/Divisiona / b21 / 7 = 3
%Modulusa % b23 % 7 = 2
**Exponenta ** b2 ** 4 = 16
//Floor Division – Rounds down to nearest whole numbera // b 9 // 2 = 4
-9 // 2 = -5

str() Function

To concatenate a number with a string in Python, first you need to convert number to string using str() function, otherwise Python will give TypeError.

TypeError: can only concatenate str (not “int”) to str

age = 32
print("Hello, I'm " + age + " years old.")

str() function converts number to string

print("Hello, I'm " + str(age) + " years old.")
# Hello, I'm 32 years old.