In the heart of every good programming language, including Python, are the variables. Variables are an awesome asset to the dynamic world of the web. Variables alone are dynamic by nature. However, Python is pretty smart when it comes to variables, but it is sometimes quite a pain. Python interprets and declares variables for you when you set them equal to a value. Example:
Isn’t that cool how Python figured out how a and b were both numbers. Now, let’s try it with the mindset of wanting the 0 to be a string and the 2 to also be a string to create a new string “02”.
Ah, see! Now, it thinks they are both strings simply because we put them in quotations. Don’t worry if you don’t understand strings yet, just note that they are not numbers or integers. This is really awesome, but as with any element or practice in a programming language there is always the flip side, especially with this auto declaration thing. Suppose we started off with “0” being a string, but we change our mind and want it to be a number. Finally, we decide that we want to add it to the number 2. Python bites us with an error. This brings us to the idea of casting the variable into a certain type.
Whoa, what is that int() thing? This is how you cast one variable type into another. In this example, we cast the string 0 to an integer 0. Let’s take a quick peak at a few of the important variable types in Python:
- int(variable) – casts variable to integer
- str(variable) – casts variable to string
- float(variable) – casts variable to float (number with decimal)
Like I said, those are just the most commonly used types of casting. Most of the other variable types you typically wouldn’t want to cast to.