Translate in Your language

Thursday, 2 April 2020

Learning Python Part - 12: Python Numbers

In previous part, we talked about different types of literals in Python programming language. In this post we will explore Python numeric literals which actually refers to Python numbers.

There are four built-in data types for numbers:

  • Integer
  • Long Integer
  • Floating Point Number
  • Complex Number

We can use the type() function to know which class a variable or a value belongs to and the isinstance() function to check if an object belongs to a particular class.

Integers:

  • Integers can be of any length, it is only limited by the memory available.
  • Integers are further classified as:

  • Normal integers:
    • Example: 
a = 1987
print(a)
print(type(a))
print(isinstance(a, int))
  • Octal literals (base 8):
    • A number prefixed by 0o (zero and a lowercase "o" or uppercase "O") will be interpreted as an octal number
    • Example: 
a = 0o10
print(a)
print(type(a))
print(isinstance(a, int))

  • Hexadecimal literals (base 16):
    • Hexadecimal literals have to be prefixed either by "0x" or "0X".
    • Example: 
hex_number = 0xA0F
print(hex_number)
print(type(hex_number))
print(isinstance(hex_number, int))

  • Binary literals (base 2):
    • Binary literals can easily be written as well. They have to be prefixed by a leading "0", followed by a "b" or "B":
    • Example: 
x = 0b101010
print(x)
print(type(x))
print(isinstance(x, int))

Long Integers:

  • Python 2 used to have two integer types: int and long. There is no long integers in Python 3 anymore. 
  • There is only one "int" type, which contains both "int" and "long" in Python version 3. 
Floating Point Number:
  • A floating point number is accurate up to 15 decimal places. 
  • Integer and floating points are separated by decimal points. 1 is integer, 1.0 is floating point number.
  • Example:  
a = 13.06; b= 3.1515e-10
print(a, b)
print(type(a))
print(type(b))
print(isinstance(a, float))
print(isinstance(b, float))


Complex Number:

  • Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part. 
  • Example:
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
print(type(a))
print(isinstance(a, complex))

No comments:

Post a comment

Followers

Popular Posts This Week