Python Lesson 4: Variables

Variables are what we use to store and handle data. We can easily tell when something is a variable, as it will be followed by an equals sign (=)

You can think of variables as a box that stores our data, or even as a nickname for our data. Let's look at an example of a variable:

X = "Hello"

In this example, X is the variable that will represent our string, "Hello". Our string is stored within this variable. You can think of this as if we have a box that we have written "X" on and we've stored the word "Hello" within it. Or, you can think of X as a nickname for "Hello"- when we call for X, "Hello" will show up. But what if we wanted X to represent multiple strings, like this?:

X = "Hello"
X = "Goodbye"
(print(X))

If we were to run this code, we would only see "Goodbye" displayed on the screen. This is because each variable can only represent one thing at a time, so it will represent the most recent data that was assigned to it. But, if we did this:

X = Sam
print("Hello, " + X)
X = Bob
print("Hello, " + X)

We would get this output:

Hello, Sam
Hello, Bob

This is because we switched what X meant halfway through our code. So, think of "=" as meaning "contains/holds" or "is the nickname of", like this:

Y = "No" is like saying that Y holds/contains "No" (where Y is our box and "No" is what we're putting inside that box)

X = "Hi" is like saying that X is the nickname of "Hi"


You may be wondering, "what's the point in creating variables?". While the usefulness of variables can depend on the project, they're especially useful when you'll need to reuse data multiple times. Let's say we wanted to keep using someone's name in the below print function. We can do it like this:


print("Hello, Joanna")
print("How are you, Joanna?")
print("Joanna?")

But of course, the more complicated the string is that we want to reuse, the more impractical this would become. Instead, we can assign the name Joanna to a variable. Let's try this instead:

name = "Joanna"
print("Hello, " + name)
print("How are you, " + name + "?")
print(name + "?")

Both of these are valid methods that will produce the same results, but the second will become more practical the longer the string is or the more you need to keep reusing it. On top of this, it makes it much easier to update your code- if you decide to change this name to something else, there's no need to manually go back and edit every single instance of it; just change the string that the variable represents. So, you'll want to get comfortable with using variables.


Lesson Recap:

  • Variables can be identified by the equals sign next to them.
  • Variables hold data. The value on the left is like a nickname for our data on the right.
  • Variables can make working with long strings much faster. They also make it much easier to change the string later on.

In the next lesson, we'll learn about Snake case and properly naming variables.