Python Variables
Aug 21, 2023
DataSciencePursuit
A variable is a way to store a value/data in computer memory as a name that can be used to recall, reuse and update/change the data.
Variables apply to data of different types, but we'll continue to work with numbers for now until we learn about other data types.
Variable assignment
To create a variable, you use the following syntax to assign a value to it:
variable_name = value
You have whatever variable name you choose and then an equal sign (assignment operator) and then the value/ data you want to store.
Let's look at an example, let's create a variable for age with the value 32 and the variable name age.
age = 32
We do not get any output since the operation is happening in the background. To see if it worked, we recall the variable by typing its name.
age
32
Great, we get 32. The variable age can now be used the same way you would use the number 32. For example, to calculate how old this person will be in 10 years, we can write 32 + 10 or we can write age + 10, both will give us 42.
age + 10
42
This applies to all the arithmetic operations we learned in the previous lesson.
Naming variables
There are some things to consider when naming variables. First, we have syntax rules i.e. you will get an error if you break the rules and there are general recommendations for readability and consistency.
Syntax
-
Include only letters, numbers, and underscore ( _ )
- Can not use spaces
- Can not use special characters (other than underscore)
- Can't start with a number (which also means a number by itself cannot be a variable name either)
Let's say we named our age variable current age:
current age = 32
Cell In[4], line 1 current age = 32 ^ SyntaxError: invalid syntax
For Python we have a style guide called PEP 8, which recommends using lowercase letters and underscore '_' instead of spaces (snake case).
Let's change our name accordingly and we will output it to the screen in the same cell.
current_age = 32
current_age
32
money$ = 100
Cell In[6], line 1 money$ = 100 ^ SyntaxError: invalid syntax
Starting with numbers:
1 = 32
Cell In[7], line 1 1 = 32 ^ SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
1age = 32
Cell In[8], line 1 1age = 32 ^ SyntaxError: invalid decimal literal
Using numbers otherwise is permitted:
age1 = 32
age1
32
Note: You will also get syntax errors if you do not follow the variable assignment syntax, for example, by forgetting the value.
Best practices
Try to use descriptive but short names. This will help you and other people more quickly understand what the variable is for.
Name error
Name errors happen when you try to recall a variable that doesn't exist.
current_ages
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[10], line 1 ----> 1 current_ages NameError: name 'current_ages' is not defined
We created the variable current_age (without the s). When recalling variables, you need to write the name exactly as you created it. For example, use the same case (always using lowercase will lessen your probability of getting name errors).
current_age
32
Optional tip: Jupyter has tab code completion. You can type c, then click tab and it will auto-complete the variable name. If you had many variable names that start with c then you will get a list of variables to choose from, click the one you need.
You can also get name errors if you restart or shut down the kernel. From the last module, we learned that restarting the kernel will clear computer memory. The same happens when we shut it down. It did not matter then as we were not saving anything, but now we are. If you restart the kernel and attempt to recall the variable without running the code to assign it again, you will get an error.
In the example below, I have restarted the kernel.
current_age
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[1], line 1 ----> 1 current_age NameError: name 'current_age' is not defined
The kernel may restart on its own. Python or your browser your computer could crash and everything in memory will get erased. The kernel will also die if you accidentally close the Jupyter Notebook terminal (the tab that pops up right after opening Jupyter Notebook) or the Anaconda prompt.
Updating variables
Let's create a new variable for my bank balance.
bank_balance = 100
bank_balance
100
Let's say I got $20 in my bank account. There are three ways to update this variable.
#1 You can reassign the variable with the new value which will overwrite/replace the old value:
bank_balance = 120
bank_balance
120
#2 You can first add 20 to bank_balance then reassign the result to bank_balance, all in 1 line:
bank_balance = bank_balance + 20
bank_balance
140
Python first evaluates what is after the equal sign which is 140 then assigns that to bank_balance.
#3 A short form of the above code:
bank_balance += 20
bank_balance
160
The +=
tells the computer to first ass 20 to bank_balance then assign that
back to bank_balance.
This operation works with all the other operators we learned. For example, if my bank balance was 20 times more, I could have:
bank_balance *= 20
bank_balance
3200
I'm rich!