day #7 - typecasting__in__Python
Type-Casting
python supports a wide variety of functions or methods
like: int(), float(), str(), ord(), tuple(), set(), list(), hex(), oct(), duct(), etc. type-casting in python
Example
input-
a="2"
b="3"
print(a+b)
Output-
23
#You might be expecting that the answer will be 5.
# But the answer will be 23 because the computer is considering the variables A and B as strings.
Two types of type-casting-
1. Explicit Conversion (means I'm doing )
The conversion of one data type into another data type, done via developer or programmer's intervention or manually as per the requirement, is knows as explicit type conversion.
ex.
intput-
string="67"
number = 7
string_number = int(string) # throws an error of the string is not a valid integer
sum= number + string_number
print("the sum of both the number is: ",sum)
output-
the sum of both the numbers is 74
2. Implicit Conversion (python is doing it automatically )
data types in python do not have the same level i.e ordering of data types is not the same in python some of he data types have higher-order and some have lower order.
while performing any operations on variables with different data types in python
one of the variables data types will be changed to the higher data types.
# implicit conversion
Input--
# python automatically converts
# a to int
a=7
print(type(a))
# python automatically converts b to float
b= 3.0
print(type(b))
# python automatically converts c to float as it is a float addition
c=a+b
print(c)
print(type(c))
Output--
<class 'int'>
<class 'float'>
10.0
<class 'float'>
Comments
Post a Comment