2. Defining scalar variables#

In addition to being used as a calculator, Python can store inputs or outputs into variables using the assignment operator (=). If a semicolon ; is placed at the end of a statement, the value of that expression is calculated but not displayed on the screen.

# Define a
a = 2
print(a)
a;
2
# Define b
b = 5
b
5
# Compute c
c = a + b ** 2   # exponentiation is two asterisks (not carat!)
print(c)
27
# Compute a different value for c
c = a + 2 * b
print(c)
12

“Restart and run all” or it didn’t happen#

With Jupyter notebooks, you have the power to run cells in any order you want. And with great power comes great responsibility. It’s easy to get variables mixed up and then your notebook starts giving you errors; or worse someone might intentionally use this to conceal duplicitly (e.g., their notebook appears functional based on cell outputs, but actually isn’t when executed from top to bottom).

So if you ever need to reset anything, the easiest way is to go to Runtime > Restart session and run all on Colab or Run > Restart Kernel and Run All Cells... on Jupyter Lab. This clears all variables and outputs from the workspace and runs your notebook from top to bottom.

Note

If you’re coming from MATLAB, you may be familiar with putting clear; close all; clc; at the top of your script. This is essentially equivalent.

Without rerunning all the cells, you can always just restart the kernel (equivalent to clear in MATLAB). Try that now by clicking Runtime > Restart session or Kernel > Restart Kernel... and then try running the next cell, which shows the variable you computed before clearing the runtime.

c
12

One more data type#

The final data type we should cover is the Boolean (bool), which represents True or False. There are a couple of ways to do this, either with a literal or an expression. Note that in Python, to check for equality between two things uses the double equals sign (==).

a = True
print(a)
b = 1 == 2
print(b)
True
False