Demystifying Python Variables: A Beginner's Guide (+Examples)

Demystifying Python Variables: A Beginner's Guide (+Examples)

Python is a popular and efficient high-level programming language that can be used to create web applications, games, scientific computing, data analysis, artificial intelligence, and a lot more.

Python syntax allows you to write clean code that is easy to read, debug, and extend. Because of its readability, it is an excellent language to learn as a beginner getting started in programming. To progress as a Python programmer, you must understand variables and how to use them effectively in your projects.

In this article, we'll look at Python variables and how to create them. We'll also go over some best practices and common mistakes to avoid when working with variables.

What are Python Variables?

Variables are like containers for storing data values. And the names we chose for variables are commonly known as identifiers. In Python, variables can be used to store data like integers, strings, lists, and dictionaries. Storing values in a variable helps you access, modify, and reuse them throughout the project.

In Python, variables are created once you give or assign a value to them.

For example:

x = 10
z = "Strong"
print(x)
print(z)

In the example above, "x" and "z" are the variables, while "10" and "Strong" are the values assigned to them.

How to Name and Use Variables in Python

When naming and using variables in Python, there are a few rules and conventions to follow. Ignoring some of these rules will lead to errors in your code. These guidelines are intended to make your code more readable, understandable, and maintainable.

When working with variables, keep the following rules in mind:

  1. Variable names are limited to letters, numbers, and underscores. They should begin with a letter or an underscore rather than a number. For example, you can refer to a variable as "my_variable" rather than "2my_variable".

  2. Variable names cannot contain spaces or special characters, but underscores can be used to separate words. There are three techniques you can use to make variable names with more than one word more readable.

    • Camel Case: All words, except the first, begin with a capital letter. Example: myFullName = "John Doe"

    • Pascal Case: The first letter of each word is capitalized.

    Example: MyFullName = "John Doe"

    • Snake Case: An underscore separates each word, with all letters in lowercase. Example: my_full_name = "John Doe"

  3. A variable name cannot contain any Python keywords or function names. Do not, for example, use the word "import" as a variable name; Python has reserved it for a specific programmatic purpose.

Some Variable Naming Conventions:

  1. Variable names should be descriptive but not too short or long. For example, full_name is preferable to f_n, and full_name is preferable to my_full_government_name. 😂

  2. Separate words in variable names with lowercase letters and underscores (the snake case technique). Python, on the other hand, suggests a snake case.

As you write more programs, remember to name variables as clearly and concisely as possible. This will aid in the readability and comprehension of your code.

Some examples of good variable names:

  • first_name

  • my_story

  • num_of_items

  • my_full_name

Some examples of variable names to avoid:

  • import

  • my name

  • numofitems

  • 2myname

Python has a set of keywords that are reserved words and cannot be used as variable names, function names, or other identifiers:

Python Keywords

How to Avoid Name Errors When Using Variables

Python is case-sensitive, and so are Python identifiers. my_full_name is different from My_full_name.

For example:

my_variable = "Python"
print(My_variable)

Output:

Traceback (most recent call last):
  File "/Users/user/PycharmProjects/HelloWorld/app.py", line 2, in <module>
    print(My_variable)
          ^^^^^^^^^^^
NameError: name 'My_variable' is not defined. Did you mean: 'my_variable'?

Another example of a name error:

proclamation = " I will make it in tech"
print(proclammation)

Here’s an example of the traceback error that Python provides after you’ve mistakenly misspelled a variable’s name:

Traceback (most recent call last):
  File "/Users/user/PycharmProjects/HelloWorld/app.py", line 2, in <module>
    print(proclammation)
          ^^^^^^^^^^^^^
NameError: name 'proclammation' is not defined. Did you mean: 'proclamation'?

The program's output indicates an error on line 2 of the file. The error is a name error, indicating that the variable being printed, "proclammation" is not defined.

This error usually occurs when a variable's value is not set before using it or when the variable's name is misspelled. Python does not spell-check code, but it does ensure that variable names are consistent.

For example:

consistenci = "What you need to make it in tech"
print(consistenci)

Output:

What you need to make it in tech

The variable name "consistency" is misspelled in this example as "consistenci" but the program still runs because the variable names match. Programming languages value consistency over correct or incorrect spelling.

How to Assign and Reassign Variables in Python

In Python, there is no command for declaring a variable, so you create a variable the moment you assign a value to it. Based on the data in the variable, the interpreter automatically determines its type. In other words, we will directly initialize the variable with any value. Initialization is the process of assigning a value to a variable.

Variables, as previously stated, are created when they are first assigned a value. The equal sign (=), also known as the assignment operator, is used to assign a value to a variable.

age = 30
print(age)

The code above prints the value of age on the screen, which is 30. That's it. You just assigned a variable.

Reassigning Variable

A variable’s value can be reassigned at any time during the execution of the code. This means that once a variable has been created and assigned a value, it can be reassigned to a new value. Variables are called variables because their values can be varied. 😉

Take a look at the following example:

message = "I need a cup of coffee."
print(message)

message = 75
print(message)

Output:

I need a cup of coffee.
75

Reassigning a value to a variable does not change the original value. The original value remains in memory, but it is not accessible from the variable anymore.

How to Assign Multiple Variables at Once

You can assign values to multiple variables at the same time using a single line of code. This technique is mostly used when initializing a set of numbers. This helps to shorten your program and makes it easier to read and understand.

Messi, Ronaldo, Mbappe = 8, 7, 3
print(Messi, Ronaldo, Mbappe)

Output:

8 7 3

You must use commas to separate the variable names and values, and Python will assign each value to its respective variable. Python will correctly match them up as long as the number of values matches the number of variables.

Assigning One Value to Multiple Variables

You can also assign one value to multiple variables in a single line of code.

Messi = Ronaldo = Maradona = Pele = "Greatest of All Time"
print(Messi)
print(Ronaldo)
print(Maradona)
print(Pele)

Output:

Greatest of All Time
Greatest of All Time
Greatest of All Time
Greatest of All Time

Swapping Variables

Swapping means interchanging values. To swap Python variables, you don’t need to do so much. You just need to use the same syntax to swap the values of two variables

x, y = "blue", "red"
x, y = y, x
print(x, y)

Output:

red blue

Constants

A constant is a variable whose value remains the same throughout the life of a program. It should not be changed or reassigned. However, because Python lacks a built-in function for constant types, the Python community established a naming convention: use uppercase letters to indicate that a variable should be treated as a constant and should never be changed.

MAX_SPEED = 753

When you want to treat a variable as a constant in your code, write the name of the variable in all capital letters.

Comments

In most programming languages, comments are a very useful feature. Because, as your programs get longer and more complicated, adding comments in the form of notes to explain the overall approach to the problem you're trying to solve will help you remember and understand them in the future.

A comment allows you to write notes in your spoken language within your programs.

How to Write Comments

In Python, the hash mark (#) indicates a comment. Anything following a hash mark in your code is ignored by the Python interpreter.

For example:

# Hello to all Developer Newbies.
print("Hello World!")

Python will ignore the first line and execute the second.

Code comments are used to explain the intended functionality and implementation details. When we work on a project, we understand how everything fits together. However, when we return to the project after some time has passed, we may forget some details. Good comments can save time by providing a clear summary of our overall approach.

Meaningful comments are essential for those aspiring to be professional programmers or collaborate with others.

How to Delete Variables in Python

If you want to delete a variable in Python, you can use the del keyword.

For example:

my_full_name = "John Benedict Doe

del my_full_name

This will remove the variable my_full_name from your namespace. Attempting to access my_full_name after running this code will result in an error.

You can also delete multiple variables at once by using the del keyword with a list of variable names:

del my_full_name, my_name, first_name

In general, you won't need to delete variables all that often. However, there are a few instances where it may be advantageous:

• When you've finished a large data structure and need to free up some memory

• When you want to ensure that a variable cannot be accessed or modified in the future

• When you want to avoid name conflicts when adding new variables

Remember that once a variable is deleted, it is gone forever. There is no way to recover it, so only delete variables that you no longer need.

Local and Global Variables in Python

When working with variables, you need to keep in mind the scope of the variable. The scope of a variable is the section of your code where the variable is accessible in a program. When you create a variable in Python, it is either local or global.

Local variable

A local variable is one that can only be accessed or modified within the scope or block of code in which it is defined. For example, if you create a variable within a function, it will only be available within that function.

def my_function():
    car = "Benz"  # This is a local variable inside the function.
    print(car)


my_function()

Output:

Benz

In this example, the variable car is declared as a local variable within the function. This means that it can only be accessed from within this function. If we try to access it outside of the function, we will get an error:

def my_function():
    car = "Benz"  # This is a local variable inside the function.
    print(car)


my_function()

print(car)

In this example, attempting to access car outside of the function will result in a NameError, as the variable is not defined in the global scope. Try it out!

Global Variable

A global variable is one that is defined outside of any function or class. They can be accessed and modified throughout the program, including within functions and classes. For example, if you create a variable at the top of your program (outside of any functions), it will be globally available throughout your program.

car = "Benz"  # This is a global variable.


def my_function():
    print(car)  # Accessing the global variable inside the function.


my_function()  # Output: car

print(car)  # Output: car, because 'car' is a global variable and can be accessed outside the function.

In this example, the variable car is declared a global variable. Which means that it can be accessed from anywhere in your program.

Note: You should generally avoid using global variables in your code because they can produce unexpected results and make your code difficult to debug.

The Global Keyword

There might be times when you want to use a variable throughout your code, but it has already been established inside a function. So using the global keyword, you can declare variables as global inside a function.

For example:

def myfunc():
  global x

x = "fantastic"

myfunc()

print(x)

In this example, we declare the variable x as a global variable within the function by using the global keyword. This means we have access to it from anywhere in our program, including outside of the function.

I believe we've gone over several ways to create a variable. Following that, we'll go over some common mistakes to avoid when working with variables.

Common Mistakes to Avoid When Working with Python Variables

Let's take a look at some of the most common mistakes to watch out for when working with variables.

Using Undeclared variables

For example:

print(Grace) # this will cause an error!

This will result in an error because the variable Grace has not been declared yet. We will need to try something like this:

Grace = "Blessings"

print(Grace) # this is correct!

This will declare the variable Grace and assign the value Blessings to it, then print the value of Grace to the screen.

Not Assigning a Value

This is a very common mistake most of us make by trying to use a variable without assigning a value to it.

Example

print(my_name)

This would lead to an error because my_name has not been assigned a value yet. So, we need to do that.

my_name = "Jay Z"

print(my_name)

This will print Jay Z to the screen.

Conclusion

In this article, we discussed how to assign, reassign, swap, and delete Python variables. We looked at naming rules and conventions, different types of variables, and some common mistakes to avoid.

Overall, Python variables are simple to create and use. Always use meaningful names and avoid deleting variables that you might need later. When working with functions, keep the variable scope in mind.

Now that you've learned about variables in Python, it's time to practice, practice, practice.

If you have any questions, please leave them in the comments and I'll do my best to answer them.

Happy coding!