Python Numbers

Python supports three types of number. They are integers, floating point numbers and complex numbers. They are defined as:

  • int
  • float
  • complex

ints or integers are positive or negative whole numbers without decimals. They can be of unlimited length.
Floats or floating point numbers are positive or negative with a decimal point.
complex numbers are written in the form x + yj where x is the real part and y is the imaginary part.

Number objects are created when a value is assigned into a variable.

Example:

  1. num1 = 7 # int
  2. num2 = 7.5 # float
  3. num3 = 5 + 3j # complex

You can use the type() function to verify the type of an object.

Example:

  1. num1 = 7 # int
  2. num2 = 7.5 # float
  3. num3 = 5 + 3j # complex
  4. print(type(num1))
  5. print(type(num2))
  6. print(type(num3))

Output:

<class 'int'>
<class 'float'>
<class 'complex'>

Type Conversion

You can convert one type of number into another by using int(), float() and complex() methods.

Example:

  1. num1 = 7 # int
  2. num2 = 7.5 # float
  3. num3 = 5 + 3j # complex
  4. a = float(num1) # convert from int to float
  5. b = int(num2) # convert from float to int
  6. c = complex(num1) # convert from int to complex
  7. print(a)
  8. print(b)
  9. print(c)

Output:

7.0
7
(7+0j)