Data Type for Numbers in Python
Python has three types of numeric data types. They are:
- int
- float
- complex
int
The int data type is a numeric type without fractional point.
Example:
x = 100
print(x)
Output:
float
The float data type is a numeric type with fraction point.
Example:
x = 100.70
y = 53e43
print(x)
print(y)
Output:
5.3e+44
complex
The complex data type is a numeric type with real and imaginary components denoted by j character.
Example:
z = 7j
print(z)
Output:
Type Conversion
There are functions such as int(), float(), complex() available in Python to convert a numeric value from one type to another.
The int() function is used to convert a string or float value to int type.
Example:
a = "10"
b = 20.28
#convert from string to int
print(int(a))
#convert from float to int
print(int(b))
Output:
20
The float() function is used to convert a string or int value to float type.
Example:
a = "174.57"
b = 20
#convert from string to float
print(float(a))
#convert from int to float
print(float(b))
Output:
20.0
The complex() function is used to convert a string, int or float value to complex type. This method accepts two optional arguments and returns a complex number. The first parameter is referred to as a real part, whereas the second is referred to as an imaginary part.
Example:
a = "177"
b = 50
c = 140.64
#convert from string to complex using single parameter
print(complex(a))
#convert from int to complex using double parameters
print(complex(b, 5))
#convert from float to complex using double parameters
print(complex(c, 7))
Output:
(50+5j)
(140.64+7j)
Note: A complex number cannot be converted into int or float type.