AlphaCodingSkills

Python - Numbers


Advertisements

Previous Page Next Page

Number data types store numeric values. There are three numeric types in Python.

  • int - also known as integer. It is a positive or negative number with no decimal points.
  • float - also known as floating number. It is a any real number and represented with decimal points. It also has scientific notation, E or e which denotes power of 10 (example: 7.5E2 = 7.5e2 = 7.5 x 10² = 750)
  • complex - also known as complex number. It is written as a + bj, where a and b are floating numbers and j is the square root of -1(which is a imaginary number).

type() function

The Python type() function is used to findout the datatype of a specified variable. In the below example, type() function is used to find out the datatype of numbers.

MyInt = 10
print(type(MyInt))

MyFloat = 10.5
print(type(MyFloat))

MyFloat = 7.5e2
print(type(MyFloat))

MyComplex = 5 + 5j
print(type(MyComplex))

Output

<class 'int'>

<class 'float'>

<class 'float'>

<class 'complex'>

Number Type Conversion

Python converts number data type automatically when an expression containing mixed numeric data types is evaluated.

MyInt = 10
MyFloat = 15.5
MyComplex = 5 + 5j

NewNumber = MyInt + MyFloat
print(NewNumber," belongs to ",type(NewNumber))

NewNumber =  MyFloat + MyComplex
print(NewNumber," belongs to ",type(NewNumber))

NewNumber = MyInt + MyFloat + MyComplex
print(NewNumber," belongs to ",type(NewNumber))

Output


25.5  belongs to  <class 'float'>

(20.5+5j)  belongs to  <class 'complex'>

(30.5+5j)  belongs to  <class 'complex'>

Sometimes, It is required to convert explicitly from one numeric datatype to another numeric datatype according to the operator or function parameter. This can be achieved by using the constructor function of the given data type class.

  • int(x) - converts x into an integer where x is an integer or a float number.
  • float(x) - converts x into a float number where x is an integer or a float number.
  • complex(x) - converts x into a complex number with real part x and imaginary part zero. Here x can be an integer or floating number.
  • complex(x, y) - converts x and y into a complex number with real part x and imaginary part y. Here x and y can be integers or floating numbers.

z = int(10.5)
print(z," belongs to ",type(z))

z = float(10)
print(z," belongs to ",type(z))

z = complex(5.5)
print(z," belongs to ",type(z))

z = complex(2, 3)
print(z," belongs to ",type(z))

Output

10  belongs to  <class 'int'>

10.0  belongs to  <class 'float'>

(5.5+0j)  belongs to  <class 'complex'>

(2+3j)  belongs to  <class 'complex'>

Previous Page Next Page