+ 3

Could anyone please explain the Type Conversion simply?

i don't get the point about the output came from ..

27th Dec 2016, 3:50 PM
Muthia Dewi
Muthia Dewi - avatar
2 Antworten
+ 5
Type conversions are used because data comes in many flavors. We have floats(decimals), integers (whole numbers) and strings (characters) for the most part. The type conversation functions allows us to alternate between each type when the setting is appropriate. Take the input function for example. This function takes input from the user as a string but what if our program was asking for them to enter two numbers that are separated with a space to add them? a,b=input('Enter two numbers, separated with a space to add: ').split() print(a+b) Take that scenario into consideration. Pretend the user gave the console '2 5'. So '2' will be stored in the variable a and '5' will be stored in the variable b. Note both of these values are of the String data type. So when we call on our print function to display the sum of the two variables it'll return 25. That's not at all what we wanted, we wanted the program to add the numbers but our program didn't treat them like numbers. It simply added two characters. That's why we use type conversions and considering that we want the program to add the numbers we will use the int() type conversion. To convert that character to an actual Integer. So.... a,b= input('Please enter two numbers separated by a space to add: ').spilt() a,b = int(a), int(b) #Now an Integer print(a+b) All in all, That's one of many scenarios where type conversions are extremely useful.
29th Dec 2016, 2:03 AM
Don
Don - avatar
+ 2
thank you so much for the answer
31st Dec 2016, 11:01 PM
Muthia Dewi
Muthia Dewi - avatar