+ 5
I don't really know what level is this question on, so I'll start slowly. Beg your pardon if it is obvious for you :) Let's say you have some variables in your code. You want to do operations on them - adding, validating, checking if they are equal to and so on. Depending on their types they might behave differently - numbers are added up arithmetically, while strings and lists are concatenated ("merged together"). Choosing a right data type for your variables is thus crucial. Let's say you want to tell the user what his age will be in 15 years. You ask by age = input() method. If you will just want to add the number 15 to it, you'll get an error - data type provided by input() is (always) a string. So in order to carry out a proper mathematical addition, you have to convert this string to an integer, by using int() method. You can either do it right away: age = int(input()) or in steps: age = input() age = int(age) Only then the addition will be done as you wished. To sum up, type conversion is like bringing your variable to a desired set of behaviours - if you want to do arithmetics, convert to integers or floats. If you want text operations - convert to string. If you have a tuple and want to modify it, convert to list, etc.
1st Apr 2017, 6:44 AM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar