Python – Numbers

Python – Numbers: Numeric values are stored in a number of data types. Python has three different numeric types:

  • int – also known as an integer. It is a positive or negative number with no decimal points.
  • float – also known as a floating number. It is any real number and is 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 a 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 an imaginary number).

type() function

 

The type() method in Python is used to determine the datatype of a variable. The type() method is used to determine the datatype of integers in the example below.

 

MyInt = 10
print(type(MyInt))

MyFloat = 10.5
print(type(MyFloat))

MyFloat = 7.5e2
print(type(MyFloat))

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

 

The output of the above code will be:

<class 'int'>
<class 'float'>
<class 'float'>
<class 'complex'>

Number Type Conversion

When an expression containing mixed numeric data types is evaluated, Python changes the number data type automatically.

 

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))

 

The output of the above code will be:

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

 

Depending on the operator or function argument, it may be necessary to convert explicitly from one numeric datatype to another numeric datatype. The function Object() method of the specified data type class can be used to do this. Let us see the list of types for Python – Numbers

  • 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))

 

The output of the above code will be:

10  belongs to  <class 'int'>
10.0  belongs to  <class 'float'>
(5.5+0j)  belongs to  <class 'complex'>
(2+3j)  belongs to  <class 'complex'>

 

Leave a Reply

Your email address will not be published.