Thursday, 9 March 2017

Python : Type Conversions

What is Type Conversion:


  • Converting the one type of data/one data type into another type of data/another data type.
  • In Java and .Net , Wrapper classes( wrapper classes contains some methods are available) support Type Conversion.
  • In Python language, some predefined functions are there.


Why we need Type Conversion:


  • After Reading the data into the Python application in the form of string format, Later we can convert string represented data into user required format by using type conversion.
Example1:


x= input("enter integer value: ")
print(x)
print(type(x))

y= int(x)
print(y)
print(type(y))

Output:

enter integer value: 12
12
<class 'str'>

12
<class 'int'>

Example2:

x= input("enter float value: ")
print(x)
print(type(x))

y= float(x)
print(y)
print(type(y))

Output:

enter float value: 3.7
3.7
<class 'str'>

3.7
<class 'float'>

Example3:

x= input("enter bool value: ")
print(x)
print(type(x))

y= bool(x)
print(y)
print(type(y))

Output:

enter bool value: True
True
<class 'str'>

True
<class 'bool'>

Example4:

x= input("enter complex value: ")
print(x)
print(type(x))

y= complex(x)
print(y)
print(type(y))

Output:

enter complex value: 3+4j
3+4j
<class 'str'>

(3+4j)
<class 'complex'>

Note:
  • Reading the data from the keyboard by using pre-defined function called input in python.
  • python 2.x -----> input, raw_input. ---> type conversion is implicitly done.
  • python 3.x ----> input, ---->type conversion is explicitly,programmer can be done.
  • The input function read the data from the keyboard in the form of string format only.

Limitations with respect in type conversion:

Example1:

x= input("enter integer value: ")
print(x)
i=int(x)
y=input("enter integer value: ")
print(y)
j=int(y)

print(i+j)

Output 1:

enter integer value: 4
4
enter integer value: 5
5
9

Output 2:

enter integer value: 6
6
enter integer value: 2.1
2.1

Traceback (most recent call last):
  File "E:/python_practice/type conversons.py", line 6, in <module>
    j=int(y)
ValueError: invalid literal for int() with base 10: '2.1'

Example 2:

x= input("enter float value: ")
print(x)
i=float(x)
y=input("enter float value: ")
print(y)
j=float(y)

print(i+j)

Output 1:

enter float value: 2.3
2.3
enter float value: 4.7
4.7
7.0

Output 2:

enter float value: 2.6
2.6
enter float value: 2
2
4.6

Output 3:

enter float value: 4
4
enter float value: 2
2
6.0



No comments:

Post a Comment