Variables
A variable is a meaningful name that references and can be assigned to an object or piece of data (known as a value). Every object in Python has a type containing the data (values) attributed to it and inherently possesses the ability to interact with the object itself or another object. Each variable can be given a name which makes it simpler to reference and access its values for re-use or at a later point. Python and many other programming languages allow variables to be manipulated and stored in the computer’s memory for later operations in a program. Variables are assigned to objects by using the assignment operator, =. The variable name is assigned on the left side of the = operator and an object (or objects) with some value, operations, or calculations is on the right. For example:
a = 3
Or:
y = x - 1
Python Naming Conventions
A variable name should be explicit, well-defined, and make your code more readable to others. Python and other programming languages have restrictions on what can and cannot be used to define the name of a variable. Below are the restrictions on variable names as well as recommended guidelines and naming conventions for writing readable variables.
Variable names can begin with lowercase letters (
a
-z
) or uppercase letters (A
-Z
).Valid Names:
a b c A B C
Digits (0 - 9) cannot be placed at the start of the variable name but can appear anywhere else in the variable name.
Valid Names:
a1 b2 c3 aA1 bB2 cC3 a1A b2B c3C
Invalid Names:
1a 2b 3c
The Underscore (
_
) character can be placed anywhere in the variable name. If the variable name starts with an Underscore (_) it is treated as a special case.Valid Names:
variable_name variablename_ v_a_r_i_a_b_l_e_n_a_m_e
Special Case Example:
__init__
Variable names are not allowed to have spaces. Use Underscores (_) and snake_case or camelCase instead of spaces to add style to your code and make your program more readable for others.
Valid Names:
snake_case snake_Case Snake_Case Snake_case CamelCase camelCase
Invalid Names:
snake case s nake case camel case c amel case
A variable name should be both descriptive and meaningful, not a single or random character in most cases, which clearly provides information or details about what the value is.
Descriptive Names:
add_three_nums multiply_two_nums
Non-Descriptive Names:
a abcd dhihjfs
The name of a variable can be any number of characters or length. It is recommended to limit the number of characters on a line of code to under 80, and use shorter variable names to improve readability and be concise.
Readable and Concise Names:
my_variable first_variable concise_name
Long and Unreadable Names:
myfirstvariablenameisnotveryreadableorconcise my_second_variable_name_is_also_too_long_and_difficult_to_read
Characters in a variable name can consist of letters, numbers, or underscores but cannot include exclamation marks at the end ( ! ), or hyphens ( - ).
Valid Names:
first_variable first_variable_1
Invalid Names:
first_variable! first-variable
Python variable names are case-sensitive. Variables that have different lowercase or uppercase characters from each other are unique.
Valid Names:
variable Variable VARIABLE
Be consistent throughout your code.
Consistent:
first_variable second_variable third_variable
Inconsistent:
fIrSt_VaRiAbLe secondvariable THIRDvariable_
A variable name cannot be the same as one of the specified keywords in Python.
Important: Foreword on Notation and Code Examples
Whenever you see a code section:
These sections with a grey area formatting are for code.
You will also see the terminal output of the code denoted with three forward arrows:
>>> 'Output of your code here'
You should not type the three forward arrows, >>>
, followed by the output into your IDE otherwise, you will get an error. Only type the code before the three arrows.
This will run in your IDE:
my_variable = 1
print(my_variable)
This will throw an invalid syntax error if you include >>>
in your program:
my_variable = 1
print(my_variable)
>>> 1
Keywords
The Python programming language has some reserved words, keywords, that can not be assigned as a variable name due to providing some explicit pre-defined functionality. In an IDE such as PyCharm, where the syntax is highlighted, the keywords will change to be a specific color set by the environment. Certain IDEs will allow you to change the coloring of keywords and the theme of the environment. These keywords should not be used to define the name of a variable.
Python has reserved keywords:
False break for not
None class from or
True continue global pass
__peg_parser__ def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
You can find all of the keywords in two different but simple ways.
1. Type help(‘keywords’)
in the CLI
Typing into the CLI:
>>> help('keywords')
2. Open up the PyCharm IDE and run the program below
Or by writing the short Python program:
import keyword
keywords = keyword.kwlist
print(keywords)
Assignment and Equivalence
A variable in Python acts as a reference that stores an object/value at a name. You need to initialize a variable with a value before you can use it. Initializing a variable using the assignment operator, =
sets that variables reference to an object’s data. For example, an integer, 1
assigned to a variable named integer_n
:
integer_n = 1
Or a string, ‘red apple’
, assigned to a variable named apple
:
apple = 'red apple'
1. Assignment in Mathematics
In mathematics, equals ( =
) is used to show the equality of both sides. It is common in algebra to see an equation defined using a variable ( y
) and set equal ( =
) to a number ( 3
) and/or another variable ( x
):
y = x + 3
x = 1
You could solve for y by substituting x into the equation:
y = 1 + 3
And you would find that y is equal to 4 :
y = 4
If a program started with y = x + 3
, Python would throw an error since the variable x
is referenced before it is assigned to a variable and the program would not execute.
2. Assignment in Programming
In programming, the equals ( =
) sign means an assignment and is used to assign a variable name on the left side of it to an object/value on the right. You can only have the name of a single variable on the left side of the assignment operator. Python uses =
for assignment since modern keyboards do not have a clear alternative to use a logical operator. Assigning a variable name to a value is more common than testing for equality as well. The right side of the assignment operator requires some value, previously initialized variable, or a combination of both. In programming, everything to the right of the assignment operator is considered an expression that can be reduced to a value. In the case of the previous example, in programming, you would have to assign x
to 1
before using the expression y = x + 3
:
x = 1
y = x + 3
print(y)
The variable x is initialized to the value 1 on the first line. Next, the value assigned to the variable x is substituted into the expression y = x + 3
. The right side x + 3
is calculated by obtaining the value assigned to x which is 1
and adding to 3
. The newly calculated value is assigned to the variable on the left y
. The value of y is then printed which is 4
:
x = 1
y = 1 + 3
print(y)
>>> 4
The Python interpreter recognizes automatically that both 1
and 3
are integer values and the = is assigning initialized variables on the left to values on the right. Multiple variable names can be assigned to the same value as well:
a = b = c = 1
print(a)
print(b)
print(c)
>>> 1
>>> 1
>>> 1
Python also has mutable objects which can be updated and reassigned throughout the duration of a program.
Mutability
In Python, variables are mutable. Mutable means that after a variable is created the value of the object can be updated or replaced at a later point. The Python programming language is strongly typed. Strong typing is when the type of value associated with the variable matters. The type should not change in an unexpected way through the duration of the program or while performing operations on that specific variable. Even if the value of the object is mutable or can be changed, the type of the variable is immutable or constant throughout the program.
1. Initialize the three variables below in the PyCharm IDE
Let’s define and initialize three different variables:
first_variable = 1
second_variable = 2
third_variable = first_variable + second_variable
2. Print each of the three variables
Next, print the three variables to see their outputs:
print(first_variable)
print(second_variable)
print(third_variable)
3. The outputs will be shown in the Terminal
The outputs of the print functions will be:
>>> 1
>>> 2
>>> 3
4. Update the value of third_variable
Now will we update the value of third_variable
to the integer 5.
To reassign the value of third_variable
type:
third_variable = 5
5. Print third_variable
again
Print out the third_variable
:
print(third_variable)
6. The output of the updated variable will be shown
The output of reassigning the third_variable
will be 5
:
7. Print the id of each third_variable
The same variable name can be assigned different values as the Python interpreter creates two independent objects which are stored in the computer’s memory and executed in order. The first and second instances of third_variable
in the program are two separate objects. You can see the unique object id assigned to both instances by printing the pre-defined function id()
after each initialization of third_variable
:
print(id(third_variable))
8. The id of each third_variable
will be shown
The output of each unique object id will be listed as a sequence of digits.
The first instance of third_variable
has the object id:
>>> 140716364334832
The second instance of third_variable
has the object id:
>>> 140716364334896
The id of each object will not change during or after the execution of the program.
Next Part
Throughout the next part and its sections, more beginner and core programming concepts will be covered. The next topic will pertain to data types and will be discussed in-depth with plenty of code examples and explanations.
Previous Parts
First Principles Python Part 0
A brief introduction to one of the most popular programming languages in the world, Python, can be found here.
First Principles Python Part 1
Create a Python program, write code in a .py file, successfully compile a program without error, and output the text “Hello, World!” to the terminal here.
Additional Articles on How to Setup your Developer Environment
I would recommend starting here and installing an integrated development environment (IDE) for Python, as it will make managing your code or projects significantly easier. Popular IDEs are PyCharm, Visual Studio Code, Google Colab, and the Jupyter Notebook.
Integrated Developer Environments Part 1
Integrated Developer Environments Part 2
Anaconda Installation Guide
Python Installation Guide
If you found this article to be useful please share it with your peers.
Or follow me on social media: