How To Name And Use Python Variables

How To Name And Use Python Variables

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_variable is easier to read than thisvariable.
  • It’s good to keep variable names as short as you can while still conveying the purpose of the variable. For example, member is a better choice than m for a variable. Along that same thought process, best_choice is better than bc for 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_variable is 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!

and except lambda with
as finally nonlocal while
assert false None yield
break for not try
class from or is
continue global pass else
def if / elif raise True
del import return in

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:

  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.

  File "c:/python/tutorialstuff/pythonvariables.py", line 1
    7pot_club = True
     ^
SyntaxError: invalid syntax

Don’t try to use spaces in your variables!

  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.

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.

python variable name error

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.

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.

<class 'int'>

<class 'bool'>

<class 'str'>

<class 'float'>

<class 'list'>

<class 'tuple'>

<class 'dict'>

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

Summary

  • 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.¬†‚Äčname‚Äč and¬†‚ÄčName‚Äč are 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.

    • Example: coffee_is_great
  • 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 ūüėä