Python Numbers
Python supports numeric data types to store numbers and perform mathematical operations.
These numeric types are simple to use and automatically assigned when you give a value to a variable.
There are three numeric types in Python:
intfloatcomplex
Variables of numeric types are created when you assign a value to them.
python
x = 10
y = 10.5
z = 2 + 3j
Integer (int)
The
int type is used to store whole numbers, positive or negative, without decimals.python
x = 10
print(type(x))
python
y = -50
print(y)
python
z = 123456
print(z)
Float (float)
The
float type is used to store numbers with decimal points.python
x = 10.5
print(type(x))
python
y = 3.14
print(y)
python
z = -0.75
print(z)
Complex Numbers (complex)
Complex numbers are written with a real part and an imaginary part.
The imaginary part is written using
j.python
x = 3 + 5j
print(type(x))
python
y = complex(2, 4)
print(y)
python
z = 5j
print(z)
Access Real and Imaginary Parts
python
x = 4 + 6j
print(x.real)
print(x.imag)
Type Conversion (Casting Numbers)
Python allows converting one numeric type into another using casting functions.
Convert to Integer
python
x = int(9.8)
print(x)
python
y = int("100")
print(y)
python
z = int(5.0)
print(z)
Convert to Float
python
x = float(10)
print(x)
python
y = float("3.14")
print(y)
python
z = float(7)
print(z)
Convert to Complex
python
x = complex(5)
print(x)
python
y = complex(2, 3)
print(y)
python
z = complex("4+6j")
print(z)
Important
- You cannot convert a complex number into
intorfloat
Random Number
Python has a built-in module called
random to generate random numbers.To use it, you must import the module first.
python
import random
Generate a Random Integer
python
import random
print(random.randint(1, 10))
python
print(random.randint(100, 200))
python
print(random.randint(0, 5))
Generate a Random Float
python
import random
print(random.random())
python
print(random.uniform(1.5, 5.5))
python
print(random.uniform(0, 1))
Choose a Random Value from a List
python
import random
numbers = [10, 20, 30, 40]
print(random.choice(numbers))
python
names = ["Python", "Java", "C++"]
print(random.choice(names))
python
colors = ["red", "green", "blue"]
print(random.choice(colors))
Check Numeric Type
You can use
type() to check the numeric data type.python
x = 10
print(type(x))
python
y = 10.5
print(type(y))
python
z = 2 + 3j
print(type(z))
Summary
- Python has three numeric types:
int,float, andcomplex - Numeric variables are created when values are assigned
- Type conversion allows changing numeric types
- Complex numbers use
jfor the imaginary part - The
randommodule is used to generate random numbers type()checks the numeric data type
Exercise
- Create one variable of each numeric type
- Convert an integer to float and complex
- Generate a random number between 1 and 100
- Print the real and imaginary part of a complex number