Tuesday, 25 June 2019

Type Casting


Type casting:

Converting from one data type to another data type.

There are two types:

1.       implicit type casting
2.       Explicit type casting

Explicit type casting:

Explicit type casting is done by the programmer.

Example:


>>> int(123.67)
123
>>> int(10+5j) #Error
>>> int(True) #Converting from Bool to integer
1
>>> float(10) #converting from int to float
10.0
>>> float(True)
1.0
>>> float(3+4j) # can't convert complex data type to float
output: Error
TypeError: can't convert complex to float
>>> 
int(a) # Error bcoz complex data types type casted to int
c=”123” # here c is str data type
int(c) # here str to int converted

Note:
1.        We can convert from any data type to int or float except complex type.
2.        Whenever we are trying to convert str data type to int/float, it is mandatory str should be either int/float literal.
Ex:
>>> a="123"
>>> int(a)
123
>>> b="10.5"
>>> float(b)
10.5
>>> 
Complex()
>>> complex(10)
(10+0j)
>>> complex(10.4)
(10.4+0j)
>>> complex("hel")
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    complex("hel")
ValueError: complex() arg is a malformed string
>>> complex(True)
(1+0j)

a=123.456 # a is float variable

int(a) #now data is converted   #from float to integer.
b=True
int(b) or int(True)
#1
c=False
int(c) -> 0 displays
a=2+3j
int(a) # Error bcoz complex data types type casted to int
c=”123” # here c is str data type
int(c) # here str to int converted

complex(x,y):
We can use this method to convert x and y into complex form such that x will be real part and y will be imaginary part.
Ex:
complex(10,-2) -->10-2j
complex(True,False)-->1+0j

Bool()
Converting from other data types into bool type.

Ex:
bool(0)àFalse
bool(1)->True
bool(“”)->False
>>> bool("True")
True
>>> bool("False")
True
>>> bool(False)
False
>>> bool(10-3j) # Non Zero
True
>>> bool(0-0j) # Zero
False
>>> print('python''programming')
pythonprogramming
>>> 

Next topic: Immutable
Previous topic:str data type

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(...