Understanding Numeric Types in Python: int, float, and complex

Learn about Python's three primary numeric types: int, float, and complex. Discover how to create variables of these types by assigning values and understand their use in Python programming.



Python Numbers

There are three numeric types in Python:

  • int
  • float
  • complex

Variables of numeric types are created when you assign a value to them:

Example

x = 4    # int
y = 3.2  # float
z = 4j   # complex

To verify the type of any object in Python, use the type() function:

Example

print(type(x))
print(type(y))
print(type(z))
Output

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

Int

An integer is a whole number, positive or negative, without decimals, and of unlimited length.

Example

# Integers:
x = 100
y = 34522554887711
z = -3455544

print(type(x))
print(type(y))
print(type(z))
Output

<class 'int'>
<class 'int'>
<class 'int'>
      

Float

A float, or "floating point number," is a number that is positive or negative and contains one or more decimals.

Example

# Floats:
x = 6.10
y = 7.0
z = -76.59

print(type(x))
print(type(y))
print(type(z))
Output

<class 'float'>
<class 'float'>
<class 'float'>
      

Floats can also be scientific numbers with an "e" to indicate the power of 10:

Example

# Scientific notation:
x = 38e4
y = 13E2
z = -88.7e180

print(type(x))
print(type(y))
print(type(z))
Output

<class 'float'>
<class 'float'>
<class 'float'>
      

Complex

Complex numbers are written with a "j" as the imaginary part:

Example

# Complex numbers:
x = 2 + 5j
y = 7j
z = -2j

print(type(x))
print(type(y))
print(type(z))
Output

<class 'complex'>
<class 'complex'>
<class 'complex'>
      

Type Conversion

You can convert from one type to another using the int(), float(), and complex() methods:

Example

x = 2    # int
y = 4.8  # float
z = 1j   # complex

# Convert from int to float:
a = float(x)

# Convert from float to int:
b = int(y)

# Convert from int to complex:
c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))
Output

2.0
4
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>
      

Note: You cannot convert complex numbers into another number type.

Random Number

Python does not have a random() function to generate a random number, but it has a built-in module called random that can be used to make random numbers:

Example

import random

print(random.randrange(1, 10))
Output

5