Loading lessons...
Numbers
Numbers
Python has three numeric types: int, float, and complex.
int
Whole numbers, positive or negative, with no decimal point:
x = 1
y = 35656222554887711
z = -3255522
Python ints can be as big as you want; no overflow.
float
Numbers with a decimal point or in scientific notation with an e:
x = 1.10
y = 1.0
z = -35.59
big = 35e3 # 35000.0
small = 12E4 # 120000.0
complex
Numbers with a real and imaginary part, written with a j:
x = 3 + 5j
y = 5j
z = -5j
Check the type
print(type(10)) # <class 'int'>
print(type(10.0)) # <class 'float'>
print(type(3 + 5j)) # <class 'complex'>
Convert between types
Use int(), float(), and complex():
x = 1 # int
y = 2.8 # float
z = 1j # complex
a = float(x) # 1.0
b = int(y) # 2
c = complex(x) # (1+0j)
Note: you can't convert a complex number to int or float directly.
Random numbers
Python has no built-in random number function, but the random module has plenty:
import random
print(random.randrange(1, 10))
TL;DR
- Three numeric types: int, float, complex.
- ints are unlimited size; floats use a decimal or e notation.
- Complex numbers use a j for the imaginary part.
int(),float(),complex()convert between them.random.randrangefrom the random module gives random ints.