Nearby lessons

33 of 108

Python - Base Conversion

Detailed Tutorial Notes

Eg: a=0o123

a=0o786

  • Hexa Decimal Form(Base-16): The allowed digits are : 0 to 9, a-f (both lower and upper cases are allowed) Literal value should be prefixed with 0x or 0X Eg: a =0XFACE a=0XBeef a =0XBeer Note: Being a programmer we can specify literal values in decimal, binary, octal and hexa decimal forms. But PVM will always provide values only in decimal form. a=10 b=0o10 c=0X10 d=0B10
print(a)10
print(b)8
print(c)16
print(d)2

Base Conversions

Python provide the following in-built functions for base conversions

1.bin():

We can use bin() to convert from any base to binary

Eg:

1) >>> bin(15)
2) '0b1111'
3) >>> bin(0o11)
4) '0b1001'
5) >>> bin(0X10)
6) '0b10000'
  • oct(): We can use oct() to convert from any base to octal Eg:
1) >>> oct(10)
2) '0o12'
3) >>> oct(0B1111)
4) '0o17'
5) >>> oct(0X123)
6) '0o443'
  • hex(): We can use hex() to convert from any base to hexa decimal Eg:
1) >>> hex(100)
2) '0x64'
3) >>> hex(0B111111)
4) '0x3f'
5) >>> hex(0o12345)
6) '0x14e5'

float data type:

We can use float data type to represent floating point values (decimal values)

Eg: f=1.234

type(f) float

We can also represent floating point values by using exponential form (scientific notation)

Eg: f=1.2e3

print(f) 1200.0

instead of 'e' we can use 'E'

The main advantage of exponential form is we can represent big values in less memory.

  • **Note: We can represent int values in decimal, binary, octal and hexa decimal forms. But we can represent float values only by using decimal form. Eg:
1) >>> f=0B11.01
2) File "<stdin>", line 1
3) f=0B11.01

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Python - Operators