Previous Lesson Table of Contents Next Lesson

In quantum mechanics, there is a very important constant known as Planck’s constant, which has a value of 6.62607004 × 10^-34 m^2 kg / s. Suppose you have to do a lot of calculations involving that constant. Do you want to keep writing that constant over and over again? Probably not. This is where variables are useful.

A variable is an identifier or symbol that can be used to represent a number, string, or essentially any other Python object (we’ll cover more of these later). Thus, instead of having to reuse the original number or string every single time, we can use the variable itself, which is generally much easier to remember:

planck_constant = 6.62607004 * 10**-34
print(2 * planck_constant)

This will output:


Remembering the variable name planck_constant is definitely much easier than remembering than the value of the constant itself. In addition, using variables is more robust to typing mistakes:

print(1 / 5.62607004 * 10**-34)

Oh no! We accidentally typed a 5 instead of a 6 at the beginning of the number. Unfortunately, Python will not know any better and will output:


Now imagine this number was used all over your code. This could lead to completely incorrect results that could very well go unnoticed for a long period of time. However, if you type a variable name incorrectly:

print(1 / plank_constant)

Notice that we forgot the "c" in planck. However, as we never defined a variable with the name plank_constant, Python will raise an error:

NameError: name 'plank_constant' is not defined

There will be a lot of other output, but the most important line to focus on right now is this one. Python is saying that we never defined the variable plank_constant and immediately alerts us that there was a typo, unlike in the other example.

Let’s now practice using variables in Python:

  • Create a variable assigned to you favorite number. Then output its sum with 1 and then its product with 2. (solution)

  • Create a variable x assigned to a string of your choosing. Then run the following:

    print(2 * x)

What happens? We’ll discuss more about this behavior in a subsequent lesson. However, to get a taste, feel free to read the solution.

In the mean time, feel free to continue to Lesson 4 by clicking here!