Variables and Assignment
Why Variables
In python you can perform basic calculations by directly writing numbers and operations. Python will give you the results as output. For example:
3 + 5
# Output: 8
312 - 43
# Output: 269
7 * 2
# Output: 14
9 / 3
# Output: 3
8 + 269 + 14 + 3
# Output: 294
You could write the numbers and operations every time and manually note down the results, but this can become cumbersome. Instead, you can save these values into variables to reuse them and make your code cleaner and more efficient.
sum = 3 + 5
sub = 312 - 43
mul = 7 * 2
div = 9 / 3
sum2 = sum + sub + mul + div
In Python, variables serve a fundamental role in any program. They hold the data we work with and the results of our computations. Variables also allow us to label data with meaningful names, enhancing code readability and comprehension. You can think of variables as containers that store information, similar to how a drawer holds items in the picture below. Their primary purpose is to label and store data, making it accessible throughout the code.
- A drawer labeled ‘Animals’ could contain numbers, which could represent counts of animals.
- A drawer labeled ‘Patients’ contains text, holding names or descriptions of patients.
A variable can always only store one thing at a time. When we assign a new value to a variables, the old value gets lost.
a = 5
print(a)
# Output: 5
a = 7
print(a)
# Output: 7
So in more technical words: A variable is a named storage location used to store data in memory. Variables are used to store information needed during the execution of a program. They can store values that change during the program’s execution.
How to name a variable?**
“All things are defined by names. Change the name, and you change the thing” — Terry Pratchett, Pyramids
Even though data is very diverse, variables cannot take every name. This is because they must be unique to the computer. They can contain letters, numbers and underscores ( _ ), though the latter cannot be used at the beginning of the name. All other characters and spaces are not allowed. This restriction is important because Python has to understand the input data, furthermore it has to be unique for the program. For example, if minus signs (-) were allowed for naming (which they are not!), there would be an ambiguity with the name all-animals
. Python would not know whether we meant the variable all-animals
or whether we wanted to subtract the variable animals
from the variable all
.
Instead, we could call it all_animals
, AllAnimals
, allanimals
, Allanimals
or allAnimals
.
Note that python distinguishes between upper and lower case for names. allAnimals
and AllAnimals
are not the same variable and it is not possible to switch them.
You should generally not use names, which are reserved for functions (e.g type()
). Try to find meaningful names, but try to make them relatively short, too.