Variables are important parts of a Python program. They are what allow us to create a placeholder of sorts in the code, and then we can put varying values in that placeholder. Any time you change the value of a variable, Python will keep track of it. There are some guidelines and rules you want to adhere to when using variables in Python. If you don’t pay attention to these, you will encounter various errors and create code that will be more difficult to understand. Let’s have a look at some of the things we should keep in mind when working with variables in Python.
Python Variable Naming
- Lowercase letter l and uppercase letter O may lead to confusion. Why? The first could be mistaken for a number 1, and the second for a number 0. In fact, you may have just mistaken those as you read that! The takeaway is to use care when using these characters or avoid them altogether.
- The characters that are allowed for variable names are letters, underscores, and numbers. The variable can not begin with a number, however. Underscores are good for adding readability. For example,
this_variableis easier to read than
- It’s good to keep variable names as short as you can while still conveying the purpose of the variable. For example,
memberis a better choice than
mfor a variable. Along that same thought process,
best_choiceis better than
bcfor a variable name. You want to know what the variable is for, but not have names that are out of control.
the_best_member_of_the_group_is_what_is_held_in_this_variableis valid, but probably not a good choice for a variable name.
- Don’t try to use spaces or any whitespace character in variable names. You can use the underscore as we saw above for better readability.
- Python has many dedicated function names and keywords. You need to be aware of what those are so that you don’t try to use any of them as variable names in your program! These are reserved for specific uses in the Python language.
Don’t use any of these for variable names!
|def||if / elif||raise||True|
As you write more programs, you’ll get good at creating and naming your variables. As they say, Practice makes Perfect. A good way to get a feel for variable naming is to read through the source code of the popular Python repositories available to see how the Python community is doing things.
Python Variable Name Examples
Let’s see a few examples of variables in Python.
If the first character is not an underscore or a letter from A-Z or a-z you will get an error. The at sign(@) character for example is not valid:
@dont_at_me = 1
File "c:/python/tutorialstuff/pythonvariables.py", line 1 @dont_at_me = 1 ^ SyntaxError: invalid syntax
Again, you can not have a variable begin with a number.
7pot_club = True
File "c:/python/tutorialstuff/pythonvariables.py", line 1 7pot_club = True ^ SyntaxError: invalid syntax
Don’t try to use spaces in your variables!
time of day = 'Lunch Time'
File "c:/python/tutorialstuff/pythonvariables.py", line 1 time of day = 'Lunch Time' ^ SyntaxError: invalid syntax
How To Prevent Naming Errors
As you’re writing your program, you might run into some errors. Scratch that. You will definitely run into errors! For example, let’s look at this Python code.
name = 'Jesse' print('Hi ', nam)
Ok easy enough. If we run this code, we expect to see the output, “Hi Jesse”. But here is what actually happens:
Traceback (most recent call last): File "c:/python/tutorial/pythonvariables.py", line 2, in <module> print('Hi ', nam) NameError: name 'nam' is not defined
Dang it! Do you see what happened there? There is a typo in the use of the
name variable when we try to print the message. Python sees this and gives us an error of “NameError: name ‘nam’ is not defined”. One trick you can use to help reduce incorrect spelling of variable names is to use an editor like Visual Studio Code. The Python interpreter doesn’t spellcheck code but the editor is able to inspect your code before it is even executed and will give you a squiggly line if there is a problem.
That small visual indication will alert you to the problem, then you can easily correct the spelling before trying to run the program 👍 So many programming errors come down to a typo which is the result of a single character being incorrect. Even the most experienced programmers run into these simple kinds of naming errors.
Type of Variables
In some programming languages, you need to declare the type of a variable. You don’t need to do this in Python. To set up a variable, all you have to do is write it out and assign a value to it.
my_variable = 'is good'
By assigning a value to a variable name, the memory is allocated for that variable to hold its value. Variables can hold all kinds of types such as integer, boolean, string, float, list, tuple, and dictionary. To inspect what the type of a variable is, you can use the reserved function named type(). Let’s see that in action.
print(type(['this', 'is', 'a', 'list']))
print(type(('this', 'is', 'a', 'tuple')))
Just by assigning the value to a variable, Python is able to use the correct type. It does this by inferring the value type by looking at the right-hand side of the assignment operator.
Learn More About Python Variables
- Realpython Python Variables (realpython.com)
- Python Variable Assignment Statements Rules Conventions Naming (thehelloworldprogram.com)
- w3Schools Python Variables (3schools.com)
- Dev Peps Pep 0008 (python.org)
- How To Use Variables In Python 3 (digitalocean.com)
- Guide To Python Variables (developer.rhino3d.com)
- Beginners Book Python Variables (beginnersbook.com)
- Getting The Name Of A Variable As A String (stackoverflow.com)
- Name A Special Variable In Python (tutorialspoint.com)
- Python Function And Variable With Same Name (stackoverflow.com)
- What Is The Naming Convention In Python For Variable And Function Names (stackoverflow.com)
- Python Variable_Types (tutorialspoint.com)
- Variables In Python (guru99.com)
- No spaces are allowed.
- The first character must be a letter (lowercase or uppercase) or an underscore.
- Only letters, numbers and underscores are permitted after the first character.
Variable names are case-sensitive.
Nameare two distinct, separate variables.
- Variable names should describe the data that they are referencing.
Use underscores to separate multiple words. This is called snake case style because the text resembles a snake.
- Python’s reserved keywords cannot be used as a variable name. These are words that are used for various operations in the language (like print).
These are just the basics of how to name and use variables in Python. You’ll want to be familiar with all the rules and guidelines here to help you avoid errors as much as possible in your Python programs 😊