x

Python Numbers

PREV     NEXT

  1. Python supports multiple data types like integer, floating, boolean and complex data type.
  2. But, it is not required to explicitly declare the variable with data type when we are going to use the number data type.
  3. By default, interpreter will consider data type depend upon the usage of number.

Please take below few scenarios.


i.e. n=5                it will convert the type as integer by interpreter

i.e. f=10.5            it will convert the type as float by interpreter

i.e. b=True          it will convert the type as boolean by interpreter

i.e. c=10+20j      it will convert the type as complex by interpreter

Example:

Output:

<type ‘int’>
<type ‘float’>
<type ‘bool’>
<type ‘complex’>

In machine level numbering, it is divided into multiple formats. They are,

1. Decimal Number:

This becomes under regular number format which we are using in general. We can also call it as base 10 format.

i.e. 1,2,35,89,1000,698365

2. Octal Number:

  • These are the numbers having base as 8. We can call these numbers as octal numbers.
  • In python, if the decimal number prefixed with ‘o’, then we can call it as octal number (any number starts with ‘0’, also can be called as octal number) 

Below is the octal number format representation:

  1. Consider the octal number“0o65”. If we print this octal number using print like “print (0o65)”, then we will get the result as “53”, Please refer below the complete explanation.

0o65 is equal to 6*(8**1)+5*(8**0) -> 6*8+5*1->48+5=53


  1. Consider the octal number “0251”. If we print this octal number using print like “print (0251)”, then we will get the result as “169”, Please refer below the complete explanation.

0251 is equal to 2*(8**2)+ 5*(8**1)+1*(8**0) -> 2*64+5*8+1*1->128+48+1=169

Note:

If we try to print the “print 08” or “print 09”, it will through invalid token error. Because, if any number starts (prefixed) with “0”, each digit should not cross “7” after “0”, i.e. Octal number stores “3” bits only in machine, so maximum allowed single digit range is “7”.

Example1:

Output:

Example2:

Output:

3. Binary Number:

  • The numbers having base 2 are called as  binary numbers.
  • In python, if the decimal number prefixed with “0b” or “0B”, then we can call it as binary number

Example:

Output:

174

Representation is like below

128  64  32   16   8   4   2   1

   1    0     1    1    1   1   1   0

128+32+16+8+4+2=174

4. Hexa Decimal Number:

The numbers having base 16 are called as hexa decimal numbers. In python, if the decimal number prefixed with “0x” or “0X”, then, we can call it as hexa decimal  number.

Example:

Output:

1615

Below is the explanation for above example:

PREV     NEXT



Like it? Please Spread the word!