It might seem like a straightforward concept, but variables are more interesting than you think. In an effort to expand our concept map, we’re here to cover one of the most basic programming concepts: variables in Python.
Table of Contents
- Concept Overview
- Where Can Variables Be Used?
- What If I Don’t Need a Variable?
- Is the Equal Sign the Only Way to Create a Variable?
- How Should I Name My Variables?
- Changing Over Time
Concept Overview
Most likely at some point in your life, you’ve heard the term “variable” used. Unfortunately, it has a lot of different definitions depending on the context. For example, in algebra, you might be familiar with variables like x
and y
, which are meant to represent sets of possible numbers. Meanwhile, in science, you might be familiar with concepts like dependent and independent variables (i.e., aspects of an experiment which can be manipulated to observe some outcome).
In the world of programming, variables are probably most closely associated with the kinds of variables you’ve seen in algebra. However, programming variables tend to have some unique features. For example, programming variables are not restricted to just numbers. We can use variables to “store” any type of data we want, from simpler data types like numbers and characters to more complex data types like entire data tables or objects.
In addition, programming variables are more “real” than mathematical variables in the sense that the data has to be stored somewhere. As a result, programming variables often don’t store data directly but rather store the address to where that data is stored. Of course, this varies from language to language.
That said, it’s very easy to assume that programming variables are similar to mathematical variables because the syntax often looks so familiar. For example, here’s how you might define your own variable in Python:
x = 37
Given the use of the equal sign, it’s tempting to assume that all the rules from algebra apply. For instance, you might imagine that this statement can be rearranged as follows:
37 = x
However, this is not legal code because the equal sign is not defining a relationship between x
and 37. Instead, the equal sign is often called the assignment operator. In other words, x
can be assigned the value 37, but 37 cannot be assigned the value x
. Because of this confusion, some programming languages choose different symbols for their assignment operator, such as the walrus operator (i.e., :=
) or an arrow (i.e., <-
).
Of course, as I said previously, we’re not restricted to storing numbers in our variables in Python. We can store whatever we like, including data structures and functions. In fact, as long as there is an expression on the right side of the equal sign, Python will be happy. As a result, all of the following lines of code are valid variable definitions in Python:
x = 3 + 5 y = [2, 4, 1] z = len
How cool is that? Now, in the remainder of this article, we’ll answer some of your questions about variables?
Where Can Variables Be Used?
Variables are probably one of the most fundamental features of Python, so you will see them everywhere. For example, in a normal Python program, you might see a variable defined based on user input:
name = input("Give me your name: ")
Likewise, you will also see variables used as function parameters. For example, the input function above accepts a prompt as an argument. That argument, is then saved in a variable for the function to use. Here’s what that might look like:
def input(prompt: str): print(prompt) # return user input
In fact, variables are so ubiquitous in Python, that most of the features wouldn’t work without them. For example, you can’t really use a while loop without a variable in the condition:
while some_variable: # do something
It’s possible to make the code above work using a function, but the function argument is just another variable. A similar argument can be made for if statements and other more complex structures like list comprehensions and pattern matching.
What If I Don’t Need a Variable?
Because variables are so ubiquitous, there are times where you will receive one that you don’t need, such as part of a return value from a function. In Python, we have a fun convention for dealing with these situations—the underscore. For example, you might have a list of values from which you only want the first and last. In Python, we can use iterable unpacking:
first, *_, last = ["red", "blue", "green", "yellow"]
In this example, the underscore is basically a dummy variable, which we dump blue and green into. It acts like any other variable, but it signals to the reader that we don’t care about its value.
Is the Equal Sign the Only Way to Create a Variable?
Typically, we create variables using the assignment operator. However, it’s possible to create variables in more recent versions of Python using the walrus operator. It functions almost identically to the regular assignment operator, but it can only be used in certain scenarios. For example, you might be familiar with the traditional while loop for reading lines from a file:
with open("path/to/file", "r") as text: line = text.readline() while line: print(line) line = text.readline()
Code like this is straightforward but some folks really don’t like duplicate code, so they opt for something like this:
with open("path/to/file", "r") as text: while line := text.readline(): print(line)
This code only works when using the walrus operator. You cannot swap the walrus operator out for the usual assignment operator. Likewise, the following is not legal code:
x := 37
The short explanation is that if you want to save and use a value at the same time, then you can use the walrus operator (e.g., in the context of a loop condition). Otherwise, you must use the regular assignment operator.
How Should I Name My Variables?
At their core, variables are just names given to data. As a result, you can name them whatever you like, aside from a few exceptions like starting with a number, including spaces, or using the name of a reserved keyword.
However, developers tend to agree that constraints are good for reducing complexity, so we often subscribe to a variety of conventions. For variables, the typical naming convention is to use snake_case, which constrains variable names to lowercase letters and underscores.
You may impose further naming conventions on your variables, so it is clearer what they contain. For example, there are a bunch of interesting conventions for distinguishing classes from interfaces (e.g., Fruit
vs. IFruit
). Because you don’t have to specify types in Python, you might also include some type information in the name—though I would just use type hints.
Changing Over Time
Like variables, this series is changing. With the addition of this article on variables, I think next time we’ll look at expressions. Let’s keep the concept map growing!
With that said, it’s time to call it today. Below you’ll find some related articles:
- The Haters Guide to Python
- Abusing Python’s Operator Overloading Feature
- 5 Things You Should Know Before You Pick Up Python
Likewise, here are some resources to help you learn more about Python (#ad):
- Effective Python: 90 Specific Ways to Write Better Python
- Python Tricks: A Buffet of Awesome Python Features
- Python Programming: An Introduction to Computer Science
Finally, feel free to check out my list of ways to grow the site. Otherwise, take care!
Recent Code Posts
Unpacking the Jargon Around Compilers, Interpreters, and More
Today, we're going to get a little pedantic and try to define concepts like compiler and interpreter. Of course, I ultimately don't think it matters what the exact definitions are for practical...
Generally, people think of Python as a messy language because it lacks explicit typing and static type checking. But, that's not quite true in modern times. Surely, we can take advantage of type...