Python Numbers

Python Numbers

There are three numeric types in Python:

  • int
  • float
  • complex

When assigning values to variables, numeric type variables will be created:

Example

x = 10   # int
y = 6.3  # float
z = 2j   # complex

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

Example

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

Run Example

Int

Int or integer is a complete number, positive or negative, without decimals, of unlimited length.

Example

Integers:

x = 10
y = 37216654545182186317
z = -465167846
print(type(x))
print(type(y))
print(type(z))

Run Example

Float

Floating or "float" is a positive or negative number containing decimals.

Example

Floating point:

x = 3.50
y = 2.0
z = -63.78
print(type(x))
print(type(y))
print(type(z))

Run Example

Floating point numbers can also be scientific numbers with "e", representing powers of 10.

Example

Floating point:

x = 27e4
y = 15E2
z = -49.8e100
print(type(x))
print(type(y))
print(type(z))

Run Example

Complex numbers

Complex numbers use "j" to represent the imaginary part:

Example

Complex numbers:

x = 2+3j
y = 7j
z = -7j
print(type(x))
print(type(y))
print(type(z))

Run Example

type conversion

You can use int(),float() and complex() Method to convert from one type to another:

Example

Convert from one type to another:

x = 10 # int
y = 6.3 # float
z = 1j # complex
# Convert an integer to a float
a = float(x)
# Convert a float to an integer
b = int(y)
# Convert an integer to a complex number:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))

Run Example

Note:You cannot convert plural to other numeric types.

random numbers

Python does not have random() A function to create random numbers, but Python has a function called random The built-in module, which can be used to generate random numbers:

Example

Import the random module and display a random number between 1 and 9:

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

Run Example

In Random Module Reference Manual In this section, you will learn more about the Random module.