Numbers in Python


Types of Numeric Values

In Python, there are three primary numeric types:

  • int
  • float
  • complex

Creating Numeric Variables

Numeric variables are established when you assign a value to them. Here’s how you can do it:

 
x = 11    # integer
y = 42.8  # float
z = 1j   # complex number
    

To check the type of a variable, use the type() function:

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

Integer Numbers (int)

An integer is a whole number, which can be positive or negative, and has no decimal points. Python integers have unlimited precision:

 
x = 1
y = 35656222554887711
z = -3255522

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

Floating Point Numbers (float)

A float, or floating-point number, includes a decimal point and can represent both positive and negative values:

 
x = 4.10
y = 3.0
z = -45.59

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

Floats can also be expressed in scientific notation with an ‘e’ to denote powers of ten:

 
x = 37e3   # 35000.0
y = 16E4   # 120000.0
z = -97.7e100  # -8.77e+101

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

Complex Numbers

Complex numbers in Python include an imaginary part denoted by a “j”:

 
x = 7 + 8j
y = 9j
z = -9j

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

Type Conversion

You can convert between numeric types using int(), float(), and complex() functions:

 
x = 61    # integer
y = 26.8  # float
z = 81j   # complex number

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

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

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

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

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

Note: Complex numbers cannot be converted to other numeric types.

Generating Random Numbers

Python does not have a built-in random() function, but you can use the random module to generate random numbers:

 
import random

print(random.randrange(1, 100))  # Outputs a random number between 1 and 99
    

Leave a Comment

Simple, privacy focused and free ad network for websites in need of new visitors. Free & easy backlink link building. Direct hire fdh.