Beginner Chapter 13 · 25 min read · Module 1: Python Fundamentals
Python Variables
- After this chapter you can create variables with the assignment operator and print their values.
- You can follow the naming rules and the common style rules for Python variable names.
- You can reassign a variable and swap two variables without a temporary name.
- You can use multiple assignment and unpacking in one line.
- You can explain that a variable is a name that points to a value, and check this with id().
Almost every program needs to remember things. A game remembers the score, a shop program remembers the price of an item, and a login page remembers the name that you typed. In Python, the tool for remembering a value is the variable. You give a value a name, and later you use that name whenever you need the value again.
Python makes variables very easy. You do not need to write a special word to create one, and you do not need to say what kind of value it will hold. You just write a name, an equals sign and a value. Because of this, variables are one of the first ideas that beginners learn, and one of the most important ones.
In this chapter you will learn how to create variables, how to choose good names, how to change a value later, and how to assign many variables at once. You will also learn what is really going on inside Python when you write a simple line such as age = 20. This small idea helps you avoid many bugs later.
What is a variable?
A variable is a name that you attach to a value. When you write score = 10, Python creates the value 10 in memory and then makes the name score point to it. After that, whenever you write score in your code, Python looks up the name and uses the value it points to.
Many people say a variable is like a box that holds a value. That picture is fine at the start, but a better picture is a sticky label. The label has a name written on it, and you stick it onto a value. You can move the label to another value later, and you can even stick two labels on the same value.
Creating variables with assignment
The equals sign in Python does not mean 'is equal to' as it does in maths. It means 'make the name on the left refer to the value on the right'. Python first works out the value on the right side, and only then attaches the name on the left.
name = "Asha"
age = 21
height = 1.62
is_student = True
print(name)
print(age)
print(height)
print(is_student)Each of the four variables above holds a different kind of value: text, a whole number, a decimal number and a True or False value. Python worked out the kind of each value by itself. A variable must be given a value before you use it. If you write print(city) before any line that creates city, Python stops with a NameError.
Rules for naming variables
Python is strict about what counts as a valid name. If you break one of these rules, you get a SyntaxError as soon as the program starts.
- A name can contain letters, digits and underscores only.
- A name cannot start with a digit, so
2nd_placeis not allowed butplace_2is. - Names are case sensitive, so
total,TotalandTOTALare three different variables. - A name cannot be a Python keyword such as
if,for,classorTrue. - A name cannot contain spaces or symbols such as
-,$or@.
Following the rules is the minimum. Good programmers also follow style rules so that code is easy to read. The Python community uses snake_case for variable names: all letters in lower case, with words separated by underscores, such as total_price or student_count. Choose names that explain the purpose of the value. A name like d tells the reader nothing, while days_left tells the reader a lot.
| Name | Valid? | Reason |
|---|---|---|
| user_name | Yes | Letters and underscore |
| count2 | Yes | Digit is allowed after the first character |
| 2count | No | Starts with a digit |
| my-name | No | Hyphen is not allowed |
| class | No | Reserved keyword |
| Total | Yes | Valid, but different from total |
Changing a value: reassignment
A variable can be given a new value at any time. The old value is not changed. The name is simply moved to point at the new value. Python does not even require the new value to be the same kind as the old one, although mixing kinds without a good reason makes code confusing.
points = 10
print(points)
points = 15
print(points)
points = points + 5
print(points)
points += 2
print(points)The line points = points + 5 looks strange if you think of maths, because no number equals itself plus five. In Python it is perfectly fine. Python calculates points + 5 using the current value, which is 15, and then attaches the name points to the result, 20. The shorter form points += 2 does the same job with less typing.
Multiple assignment and swapping
Python lets you create several variables in one line. You can give different values to different names, or give the same value to several names. You can also swap the values of two variables in one line, which many other languages cannot do without a third helper variable.
x, y, z = 1, 2, 3
a = b = 0
print(x, y, z)
print(a, b)
x, y = y, x
print(x, y)
first, *rest = [10, 20, 30, 40]
print(first)
print(rest)The line x, y, z = 1, 2, 3 is called unpacking. The values on the right are matched to the names on the left by position, so the number of names must match the number of values. The star in *rest collects all the leftover values into a list. The swap x, y = y, x works because Python builds the right side first and only then assigns the names.
Names point to values
Because a variable is only a name, two names can point to the same value. The built-in function id() shows an identity number for the value that a name points to. If two names show the same number, they point to the same value in memory. Numbers and text cannot be changed after they are created, so sharing a value like this is safe for them.
a = 500
b = a
print(a is b)
b = b + 1
print(a)
print(b)
print(id(a) == id(b))b = b + 1, Python creates a new value 501 and moves the name b to it. The name a still points to 500, so a is not changed.Deleting a variable and constants by convention
You can remove a name with the del statement. After del score, using score raises a NameError until you assign it again. In real programs you rarely need del because names disappear on their own when a function ends. Python also has no special keyword for values that must never change. By convention, programmers write such names in capital letters, such as MAX_SPEED, which you will study in the next chapter.
Good habits with variables
- Pick a clear, descriptive name instead of a single letter, except for tiny loops.
- Create a variable close to the place where you first need it.
- Do not reuse one name for unrelated things in the same part of a program.
- Do not use names of built-in functions such as
list,strorsum, because you will hide the real function. - Print a variable while debugging to check what it really holds.
If you follow these habits, your programs will be easier to read for other people and for you after a few weeks. Reading code is something programmers do far more often than writing it, so clear names are a real gift to your future self.
Python syntax
variable_name = valuea, b, c = 1, 2, 3a = b = valuea, b = b, afirst, *rest = sequencedel variable_nameReal-world applications
- Storing user input such as a name or an age so it can be used later.
- Keeping a running total such as a score, a bill or a counter inside a loop.
- Holding configuration values such as a file name or a tax rate in one place.
- Passing results from one step of a calculation to the next step.
- Swapping or rearranging values while sorting or processing data.
Common mistakes
Fix: Assign a value on an earlier line, and check the spelling and capital letters of the name.
Fix: Use letters, digits and underscores only, and do not start with a digit. Write total_price instead of total-price.
Fix: Pick another word, for example class_name or total.
Fix: Use a more specific name such as numbers, text or total.
Fix: Remember that both names point to the same value. Reassigning one name does not change the other.
Fix: Use lower case snake_case for ordinary variables and keep the spelling the same everywhere.
Important tips
- Read an assignment from right to left: first find the value, then attach the name.
- Use meaningful names so that you rarely need comments to explain a variable.
- Use the tuple swap a, b = b, a instead of writing a temporary variable.
- Use print() or the debugger to see the current value of a variable when something looks wrong.
- Use an editor with spell checking or auto-complete to avoid spelling mistakes in names.
Key points summary
- A variable is a name that refers to a value.
- The = operator assigns a value, it does not test equality.
- Names use letters, digits and underscores, cannot start with a digit and are case sensitive.
- Python style uses snake_case for variable names.
- Multiple assignment, unpacking and swapping can be done in one line.
- Reassigning a name moves it to a new value and leaves the old value unchanged.
- del removes a name, and using it afterwards raises NameError.
Exam and interview points
- = is assignment, == is comparison.
- Variable names are case sensitive: age and Age are different.
- Keywords cannot be used as names, and you can list them with the keyword module.
- In a, b = b, a the right side is evaluated completely before any name changes.
- In first, *rest = items the star name receives a list of the leftover items.
- A variable is created when it is first assigned, and deleted names raise NameError.
Quick revision
- Variable = name pointing to a value.
- Assign with name = value.
- Use snake_case, no spaces, no leading digit.
- Reassigning moves the name, it does not edit the old value.
- a, b = b, a swaps two variables.
- del name removes the name.
Frequently asked questions
Do I have to declare a variable before using it in Python?
No. There is no separate declaration. A variable is created at the moment you first assign a value to it. You only have to make sure the assignment happens before the first use.
Can a variable hold different types at different times?
Yes. Python is dynamically typed, so the name can be moved to a value of any kind. This is allowed, but it is usually better to keep one meaning for one name so that your code is easy to follow.
What is the difference between = and ==?
A single equals sign assigns a value to a name. A double equals sign compares two values and gives True or False. Mixing them up is a common beginner error.
Is there a limit on how long a variable name can be?
There is no practical limit, but very long names are hard to read. Aim for names that are clear and short, such as average_marks.
Can variable names contain non-English letters?
Python 3 allows many Unicode letters in names, so a name like naïve is legal. For code that other people will read, plain English letters are the safer choice.
Practise this chapter
25 practice questions Take the chapter quiz