Python Variables

Introduction

Variables are a fundamental part of any programming language. They provide a way to store, access, and remember data for later use. You can think of variables as containers that store basic information of various types, such as numbers and text, or complex data structures that are composed of combinations of those.

Python variables are dynamically typed, which means that you don’t need to explicitly declare their data types. You can assign any value to a variable, and Python will figure out its type based on the assigned value. This dynamic typing feature makes it easier and faster to write code, however, it also introduces greater possibility of unexpected errors and incorrect behavior (i.e. bugs), as well as slower program execution compared to statically typed languages.

Declaring and Using Variables

Declaring a variable is the process of defining its existence in a program. In Python, you declare variables by assigning values to them using the assignment operator (=). A first-time variable assignment is the declaration.

Here is the basic syntax for declaring a variable:

variable_name = value

In this syntax:

  • variable_name: The name you give to the variable. It’s like a label or a placeholder that represents a value.
  • value: The actual data that you want to store in the variable. This can be any valid Python data type, such as a number, a string (i.e. a sequence of text characters), or even another variable.

Example:

my_variable = 10

In the example above, my_variable is declared as a variable with that name, and also assigned the value 10, which is of type integer.

To use a variable and access its value, simply write its name it the code.

Let’s use the my_variable variable from the previous example and verify it has been declared by printing it:

print(my_variable)

Output:

10

Since my_variable has been declared and has a value, it can be printed without trouble using a print() function.

If you try to use a variable that hasn’t been declared yet in any way, you get an error.

Example:

print(not_declared_yet)

Output:

...
NameError: name 'not_delcare_yet' is not defined

Assigning Values to Variables

Variable assignment changes the value a variable stores. The syntax for assignment is the same as for variable declaration. After a variable has been declared, it can be assigned other values later on in the program.

You can assign a different data type that a variable has been originally declared with. However, it is not considered a good practice because it can lead to confusion and make the code harder to understand. It’s generally recommended to maintain consistency in the data types assigned to a variable throughout the program to ensure clarity and avoid unexpected behavior.

Here are some examples of variable assignment of various data types in Python:

x = 10  # integer
y = 3.14  # float
z = x  # assignment of a variable to another variable
name = "Luke Skywalker"  # string (text)
my_list = [1, 2, 3]  # list

Python Variable Naming Rules

The following are the rules for naming a variable in Python. Not adhering those will produce an error.

Variable name,

  • Can contain only letters (az, AZ), numbers (09), and underscores (_).
  • Must begin with a letter or underscore, but not a number.
  • Are Case-sensitive (age, Age, and AGE are considered different variables).
  • Cannot be reserved Python keywords (if, for, while, def, class, etc.).

Variable Naming Best Practices

When naming variables in Python, there are some conventions and best practices you can follow to improve code readability and maintainability.

Here are some guidelines to consider:

  • Use descriptive and meaningful names: Choose names that accurately describe the purpose or content of the variable. This makes it easier for other developers (including your future self) to understand the code without needing extensive comments.
  • Follow naming conventions: Adhere to the naming conventions recommended by PEP 8, the official Python style guide. This typically means using lowercase letters for variable names, with words separated by underscores (i.e. snake_case).
  • Avoid single-letter names: While short variable names like i or x may be acceptable in certain contexts (e.g., loop counters, coordinates), they should be used sparingly and only when their purpose is clear from the surrounding code. In most cases, opt for more descriptive names.
  • Use nouns for variables: Variable names should generally represent nouns or noun phrases that describe the data they hold. This helps reinforce the semantic meaning of the variable within the context of your program.
  • Use meaningful abbreviations: While descriptive names are important, excessively long variable names can also hinder readability. Use abbreviations sparingly, but ensure they are widely understood within your development team or community.
  • Avoid hard-to-read names: Steer clear of overly cryptic or obscure variable names that require excessive mental effort to decipher. Aim for clarity and simplicity whenever possible.

Multiple Assignments

Python allows you to assign multiple variables in a single line using convenient syntax called unpacking. To create a multiple assignment, write a comma-separated list of variables to assign on the left-hand side of the assignment operator, and a comma-separated list of values on the right. The values will be assigned to the variables in order.

Example:

var1, var2, var3 = 1, 2, 3

In the example above, var1, var2, var3 are assigned the values 1, 2, and 3, respectively.

The comma-separated list on the right actually creates a tuple, which is a type of collection data structure, and it is possible to use unpacking assignment with other data structures. Tuples and unpacking are discussed more in-depth in their respective lessons.

As a best-practice, use multiple assignment for variables that are closely related.

Multiple assignment syntax also enables a convenient way to swap the values of variables. For example, in order to exchange the values of x and y we assign x, y to y, x.

Example:

x, y = y, x

This capability indicates that Python copies the values on the right-hand side of an assignment to intermediary locations in memory before assigning them to the variables on the left-hand side.

Literals and How They are Different From Variables

In programming, literals are fixed values that are directly embedded in the source code. Examples of literals in Python include 1 (an integer), 0.5 (a floating point number), and "Hello" (a string). Python literals can also be more complex, such as the list of numbers [1, 2, 3, 4, 5].

Variables on the other hand, hold values in computer memory and can be referenced to by their given name. As the previous sections show, variables can be assigned values using literals, for example x = 10, but also using other variables.

It is important to understand what the term “literal” means because it is a fundamental concept in programming and referred to multiple times throughout this course.

Constants

Constants in a programming language are like variables that cannot be reassigned a new value. They can only be declared, assigned a value once, and used. Constants are useful because they provide a way to use meaningful names for fixed values, making the code more readable and maintainable.

Python does not support constants. However, by convention, variables whose names are all upper case are understood to be constants. Those can technically be assigned a new value, but shouldn’t.

Therefore, if you see an all-upper-case variable in code, you now know that it’s considered a constant whose value is meant to remain fixed.

Example:

GRAVITY = 9.81
SPEED_OF_LIGHT = 299792458

The example above defines two constants, GRAVITY, and SPEED_OF_LIGHT that hold values commonly used in physics.

Checking a Variable’s Type With the type() Function

Since Python is a dynamically typed language, you don’t need to declare the type of a variable when you create it. Python will automatically assign the type based on the value you provide. However, there are times when you might want to check the type, especially when debugging or writing functions that behave differently depending on the type of their inputs.

To check the type of a variable, you can use the built-in Python type() function. This function takes a single argument (the variable whose type you want to check) and returns the type of that variable.

Example:

x = 10
y = 3.14
name = "James T. Kirk"
my_list = [1, 2, 3]

print(type(x))      
print(type(y))      
print(type(name))   
print(type(my_list)) 

Output:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>

The type() function works the same way for literals as it does for variables.

Example:

print(type(10))    
print(type(3.14))     
print(type("James T. Kirk"))   
print(type([1, 2, 3]))

The output of this example is identical to that of the previous one.

Summary & Reference for Python Variables

A variable in Python is a named container used to store data values. Python variables are dynamically typed, meaning their type is inferred from the assigned value.


Declaring a variable is the process of defining its existence in the program. You declare variables by assigning values to them using the assignment operator (=).

variable_name = value

To use a variable, just write its name in your code.

print(my_variable)

Variable assignment involves changing the value a variable holds. It is achieved through the same syntax as variable declaration, enabling variables to store new values throughout the program’s execution. A variable can be assigned any valid Python data type, such as a number, a string, a list, or even another variable.

x = 10  # integer
y = 3.14  # float
z = x  # assignment of a variable to another variable
name = "Luke Skywalker"  # string
my_list = [1, 2, 3]  # list

Variable names follow these rules: (1) Must only contain letters, numbers, and underscores, (2) must begin with a letter or underscore, (3) are case-sensitive, and (4) cannot be reserved Python keywords.


Python supports multiple assignments, which allow simultaneous assignment of values to multiple variables in a single line.

var1, var2, var3 = 1, 2, 3

Literals are fixed values that are directly embedded in the source code. Examples of literals in Python include 1, 0.5, "Hello", and the list [1, 2, 3, 4, 5].


Constants in a programming language are like variables that cannot be reassigned a new value. Python does not support constants. However, by convention, variables whose names are all upper case are understood to be constants.

GRAVITY = 9.81
SPEED_OF_LIGHT = 299792458

You can determine the type of a variable or literal with the built-in type() function.

x = 10
type(x)  # --> <class 'int'>
type(3.14)  # --> <class 'float'>