Converting between data types in Python
While Python does determine the data type of a variable automatically, we often like to explicitly convert a variable from one data type to another. An example of where this is useful could be a user providing an input—for example, their age—from the terminal. The variable would have the str
data type, but we might need it as an integer. This is where converting between data types—or type casting—comes into play.
In this recipe, you will see how to receive an input from a user and convert the received string into an integer.
Getting ready
Open your code editor and start by creating a file called convert_variables.py
. Next, navigate your terminal to the same directory in which you just created the convert_variables.py
file.
How to do it…
In this recipe, we will receive the user's age as input in the form of a string. We will then convert that string into a number, add 10
to it, and convert...