Numeric data types in Python
What are numeric data types in Python? How do you use numeric data types in Python? Let's find out together with TipsMake.com!
What are numeric data types in Python? How do you use numeric data types in Python? Let's find out together with TipsMake.com!
Python has three numeric data types:
intfloatcomplex
Numeric variables are created when you assign a value to them:
x = 1 # int y = 2.8 # float z = 1j # complex
To validate the type of any object in Python, use the function type():
print(type(x)) print(type(y)) print(type(z))
Int
Int, or integer, is a number, positive or negative, that is not a decimal and has unlimited length.
x = 1 y = 35656222554887711 z = -3255522 print(type(x)) print(type(y)) print(type(z))
Float
A float, or 'floating point number,' is a positive or negative number containing one or more decimal places.
x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z))
Float can also be a scientific number, with 'e' representing a power of 10.
x = 35e3 y = 12E4 z = -87.7e100 print(type(x)) print(type(y)) print(type(z))
Complex
Complex numbers are written with j as the imaginary part:
x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z))
Type conversion
You can convert from one type to another using the methods int(), float(), and complex().
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))
Note: You cannot convert complex numbers to other number types.
Random number
Python doesn't have a built-in function random()to generate random numbers, but it does have a built-in module called `random` that you can use to generate random numbers:
For example:
Input a random modulo, and display a random number between 1 and 9:
import random print(random.randrange(1, 10))
Above are the things you need to know about numbers in Python . Hopefully, this Python lesson is useful to you.