Python – Data Conversion Functions

int( ) :

  • It is pre-defined function
  • It can convert input value into integer type.
  • On success, it returns integer value
  • On failure(if the input is not valid, raised error)
>>> int(10)
10
>>> int(23.45)
23
>>> int(True)
1
>>> int(False)
0
>>> int(“45”)
45
>>> int(“python”) # Error : Invalid input

Adding 2 numbers:

print(“Enter 2 numbers :”)
a = input()
b = input()
c = int(a)+int(b)
print(“Sum :”,c)

We can give the prompt directly while calling input() function.

x = int(input(“First Num :”))
y = int(input(“Second Num :”))
print(“Sum : “,x+y)

float() :

  • converts the input value into float type.
  • Raise error if the input is not valid.
>>> float(2.3)
2.3
>>> float(5)
5.0
>>> float(True)
1.0
>>> float(“3.4”)
3.4
>>> float(“abc”)
ValueError: could not convert string to float: ‘abc’

bool():

  • Returns a boolean value depends on input value.
  • boolean values are pre-defiend (True , False)
>>> bool(True)
True
>>> bool(-13)
True
>>> bool(0.0013)
True
>>> bool(0)
False
>>> bool(“abc”)
True
>>> bool(”   “)
True
>>> bool(“”)
False
>>> bool(False)
False
>>> bool(“False”)
True

str(): convert any input int string type.

>>> str(3)
‘3’
>>> str(2.3)
‘2.3’
>>> str(True)
‘True’

bin(): Returns binary value for specified decimal value.

>>> bin(10)
‘0b1010’
>>> bin(8)
‘0b1000’

Character System:

  • File is a collection of bytes.
  • Every symbol occupies 1 byte memory in File.
  • Every symbol stores into memory in binary format.
  • Symbol converts into binary based on its ASCII value.
  • Character system is the representation of all symbols of a language using constant integer values.
  • Examples are ASCII and UNICODE.

ASCII : (Americans Standard Code for Information Interchange)

  • Represents all symbols 1 language using constants
  • The range is 0 – 255
  • A language is at most having 256 symbols.
  • 1 byte range is (0-255)  – 2^8 value
  • Hence we represent a symbol using 1 byte memory.
                        A-65                a-97                 0-48                 #-35
                        B-66                 b-98                1-49                 $-36
                        ..                       ..                        ..                      ..
                        ..                       ..                       ..                       ..
                        Z-90                 z-122               9-57                 ..
                        ___________________________________________
                        26          +         26           +      10          +      150      <   256   symbols

chr(): Return the symbol for specified integer value.

ord():Returns the integer for specified symbol.

>>> chr(65)
‘A’
>>> chr(50)
‘2’
>>> ord(‘a’)
97
>>> ord(‘$’)
36
>>> ord(‘1’)
49
Scroll to Top