Learnitweb

Integral values in Python – an introduction

Integer is a number with no fractional part(no decimals). For example, 1, 100, 0, -999 are integers while 1.99 and 1/3 are not integers.

We can represent integral values in four ways:

Decimal (also base 10)

This is the standard system for denoting integer. For example, 1,2,75,999.

Binary (also base 2)

A binary number uses only two symbols: typically 0(zero) and 1(one). Binary numbers in Python are prefixed with 0b or 0B. Examples of binary numbers are: 0b101, 0B111.

x = 0b101
print(f'x={x}, type of x= {type(x)}')

y = 0B111
print(f'y={y}, type of y= {type(y)}')

Output

x=5, type of x= <class 'int'>
y=7, type of y= <class 'int'>

Octal (also base 8)

Octal number system uses digits 0 to 7. Octal numbers in Python are prefixed with 0o or 0O. Examples of octal numbers are: 0o123, 0O456. 0o789 is not a valid octal number as digits only 0 to 7 are allowed.

x = 0o123

print(f'x={x}, type of x= {type(x)}')

y = 0O456
print(f'y={y}, type of y= {type(y)}')

Output

x=83, type of x= <class 'int'>
y=302, type of y= <class 'int'>

Hexadecimal (also base 16)

Hexadecimal number system uses 16 symbols- 0,1,2,3,4,5,6,7,8,9 and A, B, C, D, E and F. Hexadecimal A represents decimal 10, B represents decimal 11 … Hexadecimal F represents 15. Hexadecimal numbers in Python are prefixed with 0x and 0X. Examples of hexadecimal numbers are: 0x123AB, 0X123abc, 0x456AF.

Note: In Python you can use either lowercase or uppercase letters to represent hexadecimal numbers.

x = 0x123AB

print(f'x={x}, type of x= {type(x)}')

y = 0x456AF
print(f'y={y}, type of y= {type(y)}')

Output

x=74667, type of x= <class 'int'>
y=284335, type of y= <class 'int'>

Note: Whenever you print the integral values by default decimal values are printed.