Python Numbers

Python Numbers

Python Numbers: Python has three numeric types.

  1. int
  2. float
  3. complex

When you assign a value to a numeric variable, a variable of numeric type is created.

Learn more about Python Variable:

For Example.

x = 1    # int
y = 2.8  # float
z = 1j   # complex

If you want to verify the type of an object in Python, you must use the type() function.

For Example.

x = 1
y = 2.8
z = 1j
print(type(x))
print(type(y))
print(type(z))

Output

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

Int Numbers

An integer is a whole number, positive or negative, with no decimals and an infinite length.

Integers Example:

x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))

Output

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

Float Numbers

A float, often known as a “floating point number,” is a positive or negative number with one or more decimals.

Floats Example:

x = 1.10
y = 1.0
z = -35.59

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

Output

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

Float can also be scientific numbers preceded by an “e” to denote a power of 10.

Floats Example:

x = 35e3
y = 12E4
z = -87.7e100

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

Output

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

Complex Numbers

The imaginary part of complex numbers is written by a “j”:

Complex Example:

x = 3+5j
y = 5j
z = -5j

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 = 1    # int
y = 2.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

1.0
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>

It is important to note that complex numbers cannot be converted into other number types.

Random Python Numbers

Python does not have a random() function to generate a random number, but python has a built-in module called random that can be used to generate a random number. So, import the random module and display a random number between 1 and 9.

Example

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

Output

6
Scroll to Top