Numbers and Type Casting
In this topic, we will learn about the different numeric data types used in Python and how to convert from one type to the other.
Integer and floating-point numbers are separated by the presence or absence of a decimal point. 25 is integer whereas 25.0 is a floating point number.
Complex numbers are written in the form, x + yj
, where x is the real part and y is the imaginary part.
Numeric Types in Python
Different numeric types in Python are integers, floating point numbers and complex numbers. They are defined as int
, float
and complex
types respectively. The following code shows examples of these numbers and the type of each number using the type()
method:
# Numeric Types
a = 100 # int
b = 12.57 # float
c = 5 + 2j # complex
print(a, type(a))
print(b, type(b))
print(c, type(c))
Output:
100 <class 'int'>
12.57 <class 'float'>
(5+2j) <class 'complex'>
Type Conversion
We can convert from one numeric type to another using the int()
, float()
, and complex()
methods. See the example below:
# Type Conversion
a = 100 # int
b = 12.57 # float
c = 5 + 2j # complex
# conversion from int to float:
x = float(a)
# conversion from float to int:
y = int(b)
# conversion from int to complex:
z = complex(a)
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
Output:
100.0
12
(100+0j)
<class 'float'>
<class 'int'>
<class 'complex'>