There are three numeric types in Python:
intfloatcomplex
Variables of numeric types are created when you assign a value to them.
1. int (Integer)
int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
x = 1
y = 35656222554887711
z = -3255522
print(type(x)) # <class 'int'>
print(type(y)) # <class 'int'>
print(type(z)) # <class 'int'>
2. float (Floating Point Number)
float, or “floating point number” is a number, positive or negative, containing one or more decimals.
x = 1.10
y = 1.0
z = -35.59
print(type(x)) # <class 'float'>
Float can also be scientific numbers with an “e” to indicate the power of 10.
x = 35e3
y = 12E4
z = -87.7e100
print(type(x)) # <class 'float'>
3. complex (Complex Numbers)
Complex numbers are written with a “j” as the imaginary part. They are heavily used in scientific and mathematical applications.
x = 3+5j
y = 5j
z = -5j
print(type(x)) # <class 'complex'>
4. Type Conversion (int(), float(), complex())
You can convert from one numeric type to another using the int(), float(), and complex() methods.
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) # 1.0
print(b) # 2
print(c) # (1+0j)
Note: You cannot convert complex numbers into another numeric type.
5. Random Number (random module)
Python does not have a random() function built-in to make a random number, but Python has a built-in module called random that can be used to make random numbers.
First, you must import the random module:
import random
# Generate a random float between 0.0 to 1.0
print(random.random())
# Generate a random integer between 1 and 9
print(random.randrange(1, 10))
# Generate a random integer between 1 and 100 (inclusive)
print(random.randint(1, 100))
The random module contains many other functions for shuffling lists, making choices, and generating random data.
Discussion
Loading comments...