VMware ESXi and vSphere Cluster Management
What Are Variables in Python?
Learn how Python variables refer to values, how assignment and reassignment work, how to name variables, and how variable names differ from string literals.
What Is a Variable?
A variable is a name used to refer to a value in a program. A value is data such as a number, text, or a Boolean value. Variables let a program remember information and use that information later.
A useful beginner analogy is to imagine a labeled container. The label is the variable name, and the contents are the value. You can use the label to find the contents, and you can later replace the contents with something else.
Python's technical model is a little more precise: a variable name is bound to an object. An object is Python's runtime representation of a value. Thinking in terms of names referring to objects helps explain why assigning a new value changes what a name refers to, rather than permanently changing the name itself.
Variables make programs more reusable and readable. Instead of writing the number 95 everywhere, you can give it a meaningful name such as student_score. A program can also work with changing information, such as a different score, username, or item count, without needing its instructions rewritten.
Creating a Variable with Assignment
Python creates a variable name when you assign a value to it. Assignment uses the assignment operator, written as an equals sign (=).
x = 3This statement has two parts:
- The right-hand side,
3, is evaluated as a value. - The left-hand side,
x, is associated with that value.
In this example, Python binds the name x to an object representing the integer 3. The equals sign here does not mean mathematical equality. It means “evaluate the right-hand side and assign its result to the name on the left.”
For example, x = 3 means that x now refers to 3. It does not ask whether x and 3 are equal as a mathematical equation would.
Names, Values, and Objects
It helps to separate three related ideas:
- Name: the identifier you write, such as
xorstudent_score. - Value: the data represented by the program, such as
3,"Ava", orTrue. - Object: Python's runtime representation of that value.
When Python evaluates an assignment such as x = 3, it creates or uses an object for the value and associates the name x with that object. The container analogy is helpful, but a variable is not necessarily a physical box in memory. Also, every assignment does not necessarily create an entirely new object; Python may reuse objects in some situations.
For beginner-level code, the important rule is simple: after an assignment, evaluating the name gives you the value currently associated with it.
Using a Variable
You can pass a variable to print(), a built-in function that displays a value.
>>> x = 3
>>> print(x)
3When Python evaluates x in print(x), it looks up the object currently associated with the name x. The output is the value, 3.
You can also evaluate a variable name directly in the interactive interpreter:
>>> x
3In a Python file, an expression such as x by itself does not usually display anything. Use print(x) when you want a script to show the value.
Variable Names and String Literals
An unquoted identifier is interpreted as a variable name. Text enclosed in quotation marks is a string literal: text written directly in the code as a value.
x = 3
print(x)
print('x')The output is:
3
x| Code | How Python interprets it | Output |
|---|---|---|
print(x) | Look up the value currently associated with x | The value under x, such as 3 |
print('x') | Display the literal text x | x |
Quotation marks are used to create text values, not to access a variable by name. Therefore, print(x) prints the value associated with x, while print('x') prints the one-character string x.
Reassignment: Changing the Value
Reassignment means assigning a new value to a name that already has a value.
x = 3
print(x)
x = 5
print(x)The output is:
3
5After the first assignment, x refers to 3. After x = 5, the same name refers to 5. The name remains x, but its associated value changes.
If you need to keep both values, use separate names:
old_score = 3
new_score = 5
print(old_score)
print(new_score)Choosing Valid Variable Names
A variable name is an identifier. An identifier is a valid name for a variable, function, class, or another program element.
Basic Python naming rules are:
- A name may contain letters, digits, and underscores.
- A name cannot begin with a digit.
- Spaces are not allowed.
- Punctuation such as hyphens is not allowed in an ordinary variable name. Use an underscore instead.
- Python keywords cannot be used as variable names. Keywords are reserved words with special meaning in the language, such as
class,if, andreturn. - Names are case-sensitive:
score,Score, andSCOREare different names.
| Name | Valid? | Reason |
|---|---|---|
student_score | Yes | Uses letters and an underscore |
score2 | Yes | Digits are permitted after the first character |
2score | No | Cannot begin with a digit |
student score | No | Spaces are not allowed |
class | No | It is a Python keyword |
Prefer descriptive lowercase names with underscores, a style commonly called snake_case:
student_score = 95
print(student_score)This prints:
95A short name such as x is fine in a small example or mathematical loop. In larger programs, a name such as student_score communicates purpose more clearly than a single letter.
Variables and Data Types
Variables can refer to values of different types. An integer is a whole-number type, such as 3 or 5. A string is text, and a Boolean value is either True or False.
age = 12
name = 'Ava'
is_logged_in = TrueIn simple assignments like these, you do not declare the type separately. Python determines the type of each value at runtime. This is one reason the same variable name can be reassigned to a value of another type:
message = 'ready'
message = 3Although Python permits this, keeping a variable's purpose and type consistent usually makes code easier to understand. A later lesson on Python variables and data types can explore these values in more detail.
Comments for Readable Code
A comment is a note for human readers. Python ignores text beginning with # when it runs the program.
# Number of items in the cart
item_count = 4Comments can label an assignment or explain why a variable exists. Use clear variable names first, then add comments when they provide useful context that the code cannot express by itself.
Common Problems and Fixes
Printing the Letter Instead of the Value
If the program prints the letter x instead of the value assigned to x, the name was placed inside quotation marks.
# This prints the text x
print('x')
# This looks up and prints the value of x
print(x)Using an Invalid Name
A name such as 2score causes a SyntaxError because identifiers cannot begin with digits. It may also occur when a name contains spaces, unsupported punctuation, or a reserved keyword.
# Invalid
# 2score = 90
# Valid
score2 = 90Using a Name Before Assignment
A NameError occurs when Python cannot find the name you are trying to use. Assign the value first, and check spelling and capitalization carefully.
# Incorrect
# print(score)
# score = 90
# Correct
score = 90
print(score)Unexpectedly Changed Output
If this code prints 5, that is correct:
x = 3
x = 5
print(x)The second assignment reassigns x. If both values must be retained, use different variable names.
Summary
- A variable is a name used to refer to a value during program execution.
- Python assignment uses the
=operator to bind a name to an object. print(variable_name)displays the value currently associated with that name.- Quotes create string literals, so
print('x')prints text whileprint(x)looks up a variable. - Reassignment binds an existing name to a new value.
- Good identifiers use descriptive lowercase
snake_casenames and follow Python's naming rules. - Variables can refer to integers, strings, Booleans, and other types, which Python determines at runtime.
- Comments beginning with
#document code for human readers.