+ 1

Typecasting

Can somebody explain typecasting in python?

22nd Jun 2024, 10:21 AM
Md Imties Ahammed
Md Imties Ahammed - avatar
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
22nd Jun 2024, 10:37 AM
Per Bratthammar
Per Bratthammar - avatar
+ 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?
22nd Jun 2024, 1:53 PM
Andrew [DEAD]
Andrew [DEAD] - avatar
+ 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
24th Jun 2024, 11:52 AM
Nisha Choudhary
Nisha Choudhary - avatar