I learned Python alongside SQL and R, but never really got exposed to the other languages until later on. So when Typecasting was being discussed in our class, I thought "what's the big deal?". Turns out, it's huge.
Typcasting is basically turning the variables into different data types so the program can understand what it is. That's because programming languages, just like regular languages, have rules to follow depending on what type of word is being used. For example, you can modify (conjugate) verbs to denote when the action happened, but you can't do the same for nouns.
In Python, typecasting very easy to do. In fact, by default, the language is smart enough to recognize the type without you explicitly defining it. In the below example, without telling python that "Cookie" is a string, it automatically recognizes its type --
name = "Cookie"
print(type(name))
<class 'str'>
And if you want to change the type, it has a very clean syntax --
number = 1
print(type(number))
<class 'int'>
change_to_float = float(number)
print(type(change_to_float))
<class 'float'>
Same goes with str() and bool() --
example = True
print(type(example))
<class 'bool'>
change_to_string = str(example)
print(type(change_to_string))
<class 'str'>
change_back_to_bool = bool(change_to_string)
print(type(change_back_to_bool))
<class 'bool'>
So why is easy typecasting important?
It makes your code shorter and simpler
Working with your data across databases will be easier especially if you work with mixed-type data
Your code will be less prone to errors
You will find one less item to think about when debugging
You can optimize the performance of your code
It's no wonder Python use has been increasing in the past few years. Watch out for more articles to get more tips or learn more Data Science basics. See you around, Data Divers!
Questions? Feedback? Head over to the About Me page and leave me a message. Thank you!