Python Numbers
Python gives you three numeric types:
intfloatcomplex
Assigning a value to a variable is all it takes to create one of these.
The type() function will confirm the type of any Python object.
Example
Show the type of each of these numeric variables:
Output: complete Python program
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
Int
An int (short for integer) is a whole number with no decimals. It can be positive or negative and can be as long as you like.
Example
Integers:
Output: complete Python program
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
A float, short for "floating point number", has one or more decimals and can be positive or negative.
Floats can also be written in scientific notation, where an "e" marks the power of 10.
Example
Floats:
Output: complete Python program
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Example
Floats written in scientific notation:
Output: complete Python program
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
A complex number uses a "j" to mark its imaginary part.
Example
Complex:
Output: complete Python program
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
The int(), float(), and complex() functions turn a number of one type into another type.
Note: A complex number can't be converted to any other number type.
Example
Converting between types:
Output: complete Python program
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))
Random Number
Python has no random() function for producing a random number. What it does have is a built-in module named random, which does this job.
Example
Import the random module and show a random number between 1 and 9:
Output: complete Python program
import random
print(random.randrange(1, 10))