A Beginner's Guide to Variables in Python
What is a variable in Python? Simply put, a variable is a reserved memory location for an object. Think of a variable as a ‘container’ where an object is stored. An object is assigned to a variable. Python uses = sign to assign an object to a variable. The variable is always on the left side of the = sign and the object is always on the right side of the sign. Look at the simple example below:
x = 2
In the above code, 2 is the object stored in the variable x. To access 2, we have to call the variable x, which is the point of reference for object 2.?To reiterate, a variable is not an object, it is a point of reference for an object. X is the variable and 2 is the object. We can assign variables to different data types and data structures– floats, strings, integers, Boolean values, complex numbers, lists, tuples, dictionaries, sets, etc. See some examples below:
#assigning a variable name to a dic
names = {'first': 'John','last':'Brown'}
#assigning a variable name to a list
names = ['John', 'Lloyd', bool]
#assigning a variable name to a tuple
names = ( 'John', 'Lloyd')
#assigning a variable name to a set
names = {'John', 'Peter'}
#assigning a variable name to a float
num = 2.0
#assign variable name to a string
name = "Lloyd"
Python allows us to create different variable names for the objects that we create. Python has rules that we must follow to create proper variable names. We are going to explore the type of variable names that are allowed in Python, and type of variable names that are not allowed in Python. We will also explore what the best practices are when it comes to picking variable names for your code.
Allowed Variable Names in Python
Python allows us to create only certain types of variable names. The following variable names are legal in Python:
1. We can start variable names with either lowercase or uppercase letters. We can have a variable name with only lowercase letters, and we can have a variable name will only uppercase letters. It is all legal in Python. Remember that variable names in Python are case-sensitive, so num is not equal to Num or NUM. Here are some examples of variations of variable names:
Example 1
num = 2
print(num)
Output:
2
Example 2
Num = 2
print(Num)
Output:
2
2. We can start variable names with an underscore sign ( _ )
_name = 'John
print(_name)
Output:
John'
3. We can use underscore ( _ )to separate two words in a variable name. See below:
first_name = 'John
print(first_name)
Output:
John
4. We can use numbers in a variable name as long as the number is not the first character of the variable name.
name9 = 'John'
print(name9)
Output:
John
Illegal Variable Names in Python
The following variable names are not allowed in Python:
1. We cannot start a variable name with a dash (-). We cannot use a dash (-) to separate words in a variable name. If we do any of these, our code will generate an error. See below:
Example 1
-name = 'John'
print(-name)
Output:
-name = 'John'
^
SyntaxError: cannot assign to operator
Example 2
first-name = 'John'
print(first-name)
Output:
first-name = 'John'
^
SyntaxError: cannot assign to operator
2. Variable names cannot start with a number. The example below generates a syntax error because we are trying to start a variable name with a number.
领英推荐
9name = 'John'
print(9name)
Output:
9name = 'John'
^
SyntaxError: invalid syntax
3. We cannot use space to separate words in a variable name. It will generate a syntax error. See below:
first name = 'John'
print(first name)
Output:
first name = 'John'
^
SyntaxError: invalid syntax
4. We cannot use Python reserved keywords as variable names. The following reserved keywords cannot be used as variable names. If we use any of these keywords, our code will generate an error. To find a list of keywords we can import the module keyword to extract a list of Python reserved keywords. All the words listed in the output below will generate an error if used as variable names.
import keyword
print(keyword.kwlist)
Output:
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Let’s try to use one of the words in the above list of keywords as a variable name in our code. The code below generates a syntax error because we are not allowed to use the word?False?as a variable name.
False = bool
print(False)
Output:
False = bool
^
SyntaxError: cannot assign to False
5. We cannot use Python built-in function names as variables. Built-in function names cannot be used as variable names even though they are not part of Python reserved keywords list. For example, we should not use the word?list?as a variable name because it is a built-in function in Python. If we use it as a variable name, our code will not generate an error. However, when we try to use the list built-in function in the same script to create a list, it will not work. Once we use a built-in function name as a variable name, then all references to the built-in function will not work. So, as good practice, it is good to steer clear of using all built-in function names as variable names, even the ones that are not on the reserved keyword list above.
list = [7, 4]
print(list)
# Creating a list using the list function
list2 = list((3,4))
Output:
[7, 4]
list2 = list((3,4))
TypeError: 'list' object is not callable
Best Practices for Creating Variables
When it comes to variable names, they are recommended best practices that we must adhere to. Choosing the right variable name will improve the readability of our code.
def count_number():
student_names = ['Mary','Peter','Ben','kim']
class LastNames:
Great article and very insightful.