Why would we want to change the value of a variable?


#1

Question

What are some common reasons to change the value of a variable? Why not just set the final value in the first place?

Answer

Often at times in programming you’ll make variables that you need to start off as some initial value, do some calculations, and end up with the result stored in that same variable.

For example! Say we want to convert the temperature from fahrenheit to celsius. We might have a variable, temperature = 65, that we do some calculations with. At the end, we could overwrite that variable to its corresponding celsius, temperature = 18.33.

However! If we do want to make a variable that holds a value that doesn’t change, there is a standard practice for letting everyone know a variable is meant to be a constant. If you’ve programmed in other languages, you might be familiar with the idea of making a variable a constant, meaning it cannot be changed after initialized. While we can’t do that in Python, a common practice is to make variables you want to be constants have all-caps names, like this: TEMP_FAHRENHEIT. Then you just have to be sure not to change the variable itself later in your code.


FAQ: Learn Python - Python Syntax - Updating Variables