+ 1
Typecasting
Can somebody explain typecasting in python?
3 Answers
+ 6
Hi Md Imties Ahammed,
Here are som example of type casting:
n = int(input("input an integer: "))
# Converts user input to an integer
k = 5
print(str(k) + " thousand")
# Converts k to a string and concatenates it with " thousand"
x = 15 / 2
# x becomes a float with the value 7.5
p = int(x)
# Converts x to an integer, so p is 7
+ 3
LESSON:
--> implicit type casting
(automatic type casting)
>>>sum = 5 + 5.6
# 5 (int) converts to 5.0 (float) then added to 5.6.
--> explicit type casting
(forceful type casting)
>>>num = int("5")
# string "5" converts to int 5
>>> int()
>>> str()
>>> float()
>>> bool()
UNIT TEST
>>> if "no":
print("andrew")
will this output "andrew"?
"no" is converted to bool first, what type of type casting is this?
+ 3
Typecasting consist of two types
1 implicit in which data type is automatically converted into higher data type
E. g
sum=7+65.8
print(type(sum))
It will result in float
Explicit in which data type is forcefully converted according to our choice
E. g
sum=int(7+65.8)
print(type(sum))
It will result in int