SchoolWhool
Quizzes and saved progress, freeSign in freeSign in

Python 1.3Free video11 minLesson 3 of 6 in Module 1

Variables, Keywords and Identifiers

Bind names to objects, and name variables by Python's rules.

Free sample. Everything in this module opens with a free account.

Watch or read the lesson: Variables, Keywords and Identifiers

01Variables and assignment

In the previous lesson you wrote a few lines of Python, and one of them looked something like this:

bread = 2.25

You gave a value to a variable, and then used that variable in your calculations. But there is something we did not really explore. What exactly happens when Python executes that line? Where does the value go? What does the variable actually store? And what happens if two variables refer to the same value?

These might seem like small details, but understanding them now will make a lot of things in Python much easier to understand later. So let's take a closer look.

The assignment statement

Start with one simple line of code:

total = 24.75
total
24.75

The first line has three pieces. On the left is the name total. On the right is the value 24.75. And between them is an equals sign.

Here is something important. In Python, this equals sign does not mean equality the way it does in mathematics. It does not claim that total and 24.75 are equal. It is the assignment operator: it tells Python to evaluate the value on the right and assign it to the name on the left. The entire line is called an assignment statement.

After this statement runs, you can use the name total to refer to the value 24.75. That is what the second line of the cell does: writing just total asks Python for the value the name refers to, and it shows 24.75. A name used this way is what we commonly call a variableKey termA name given to a value. In Python, a name that refers to an object..

No type declaration

Notice that you did not declare a type for total. You never told Python "this will be a number". Python works the type out from the value itself. 24.75 is a floating-point number, or float for short, and the built-in function type confirms it:

type(total)
float

The next lesson explores the different types in detail. For now, let's follow what happens when this assignment runs.

02Names and objects

When Python executes total = 24.75, you can think of it as two steps. First it deals with the right-hand side, then with the left.

Step one: the object

First, Python evaluates the right-hand side. In this case that is just 24.75. Python creates a float object representing that value.

An objectKey termA value in memory, with its type. Every object has an identity number, shown by id(). is how Python holds a piece of data in memory, and every object has three things:

  • a type, which tells Python what kind of object it is (here, float);
  • a value, which is the data it represents (here, 24.75);
  • an identity, which distinguishes that object from every other object during its lifetime.

So at this point there is a float object representing 24.75, and nothing has been done with the name yet.

Step two: binding the name

The second step is to bind the name total to that object. This is called name binding.

You might be wondering where Python keeps track of all these names. That is the job of a namespaceKey termThe table of names that exist, each with a reference to an object.: a mapping between names and the objects they refer to. So when you write total = 24.75, Python binds the name total to the float object in the appropriate namespace.

Notice where each thing lives. The object has the type and the value. The name has neither; it only refers to the object.

id: an object's identity

You can look at an object's identity with a built-in function called id. It returns an integer representing the identity of the object a name refers to:

id(total)

Run this and you will get a large integer. The exact number does not matter, and it will be different on your machine and on each run. What matters is that the identity stays the same for as long as that particular object exists.

For now, just think of id() as a way to check whether two names refer to the same object.

Two names for one object

Now let's try something interesting. Suppose you write:

previous_total = total
Predict first

Here is a question. Does Python create another float object with the value 24.75? Or does it make previous_total refer to the object you already have? Think it through before reading on.

I have a guess. Show meHide the answer

Python does not create a copy of the object here. Instead, it evaluates the right-hand side, which is the name total, by looking up the object that total already refers to. Then it binds the name previous_total to that same object.

You can verify that with id(). If the two names refer to the same object, they give the same identity:

previous_total = total
id(total) == id(previous_total)
True

You can also use the is operator, which asks directly whether two names refer to the same object:

total is previous_total
True

That is an identity check: True means both names are referring to one object. You will meet is properly in the operators lesson.

Rebinding

Now let's take this one step further. What happens if you change total? Say you write:

total = 26.25
Predict first

What do you think happens to previous_total? Will it also become 26.25, or will it stay at 24.75? Think about what you just learned about names and objects. Think it through before reading on.

I have a guess. Show meHide the answer

Let's check, printing both names:

total = 26.25
print(total, previous_total)
26.25 24.75

total is now 26.25. That is because when you wrote total = 26.25, Python evaluated the new value, created an object for it, and bound the name total to that new object.

The name previous_total was not touched. It still refers to the original object, the one representing 24.75. So now there are two names referring to two different objects.

Moving a name's reference to another object is called rebindingKey termBinding a name to a different object. The old object is unchanged, and any other name still refers to it.. It does not modify the object the name previously referred to. The float 24.75 is still there, unchanged, and previous_total still refers to it.

03Multiple assignment and swapping

Python also lets you assign several names in one statement.

Multiple assignment

Suppose you are working with a food order. You have three pieces of information: the number of items, the price, and the restaurant name. You could write three separate assignment statements. But Python also lets you assign all three in a single statement:

items, price, restaurant = 3, 24.75, "Green Bowl"
print(items, price, restaurant)
3 24.75 Green Bowl

This is called multiple assignment, and it works by sequence unpacking: Python matches the values on the right with the names on the left, in order. So items gets 3, price gets 24.75, and restaurant gets the string "Green Bowl". Pretty convenient.

Chained assignment

Now, what if you want several variables to start with the same value? Say you are tracking likes, shares and comments on a post, and initially all three are zero. You can write:

likes = shares = comments = 0
print(likes, shares, comments)
0 0 0

This is called chained assignment. Python evaluates the value on the right once, and binds all three names to the resulting object. So likes, shares and comments all refer to the same integer object representing zero. You can confirm that with is:

likes is shares is comments
True

Is it a problem that three names share one object? Not here. Integers are immutable, which means an integer object can never be changed. And if you later assign a different value to likes, the other two names will not change. It is the same rebinding behavior you saw with total and previous_total: the assignment moves the name likes to a new object and leaves the others where they were.

Swapping two variables

Here is another useful feature: swapping the values of two variables. Say you have:

a = 1
b = 2

You want to swap them, so a should become 2 and b should become 1. In some programming languages you would need an extra temporary variable to do this. Python makes it much easier. You can simply write:

a, b = b, a
print(a, b)
2 1

And that is it. The values are swapped.

So how does this work? Python evaluates the entire right-hand side first. It gets the objects currently referred to by b and a, which are 2 and 1. Only after that does it assign those objects to the names on the left. So a gets the old value of b, and b gets the old value of a, all in one statement.

This is one of those small Python features you will probably end up using quite often.

04Identifiers and keywords

So far we have been choosing variable names pretty freely: total, price, items, previous_total. Can you use absolutely anything as a variable name? Not quite. Python has some rules about naming things.

These names are called identifiers. An identifier is a name used to identify something in Python, like a variable, a function or a class. There are three rules to follow.

The three rules

Rule one is about which characters you can use. For the examples in this course we stick to letters, digits and underscores. Python also supports many Unicode letters, but simple English letters and underscores are usually the easiest choice when you are learning.

What you cannot do is put a space in the middle of an identifier, and characters like dollar signs and hyphens are not allowed either. So delivery_fee is perfectly valid. But delivery fee, with a space in it, is not. And delivery-fee does not work as a single variable name either, because Python reads the hyphen as a subtraction operator: it sees delivery minus fee.

Rule two: an identifier cannot start with a digit. So item2 is fine, but 2item is not.

Rule three: you cannot use a reserved keyword as an identifier. Keywords are coming up in just a moment.

There is one more thing to remember. Python identifiers are case-sensitive. That means total, with a lowercase t, and Total, with a capital T, are two completely different names, and Python treats them separately.

Starting with a digit

Now let's see what happens when you break one of these rules. Suppose you try to create a variable called 2nd_item and assign it the value 1:

2nd_item = 1
Predict first

Do you think Python will accept that? Think it through before reading on.

I have a guess. Show meHide the answer

No, it will not. An identifier cannot start with a digit, and Python stops with an error before running anything:

    2nd_item = 1
    ^
SyntaxError: invalid decimal literal

A SyntaxError means Python could not make sense of how the code is written. More specifically, Python reports an invalid decimal literal. Why that message? Python sees the 2 at the beginning and starts reading it as a number, a decimal literal. But then it meets letters immediately after the digit, and a number cannot contain them, so Python cannot interpret the code. (This is the message Python 3.14 prints; older versions word some syntax errors slightly differently.)

Moving the digit to the end

If you move the digit to the end, as in item_2, everything works:

item_2 = 1
item_2
1

Digits are allowed in identifiers. They just cannot be the first character.

Keywords

Now the third rule: keywords. A keywordKey termA word Python reserves, such as if, for, class, True and None. It can not be used as a name. Python 3.12 has 35. is a word that has a special meaning in Python's syntax. Words like if, for and class are keywords, and so are the values written as keywords: True, False and None. Python reserves these words for specific purposes, so you cannot use them as ordinary variable names.

For example, suppose you try to write:

class = "B"
    class = "B"
          ^
SyntaxError: invalid syntax

Python gives a SyntaxError, because class is already a Python keyword. Python expects it to be used as part of a class definition, not as a variable name.

If you are curious about the full list of keywords, there is an easy way to see them. Python's standard library includes a module called keyword. You can import it and look at keyword.kwlist:

import keyword
keyword.kwlist
['False', 'None', 'True', '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']

That gives you the list of reserved keywords in your Python version. And with the len() function you can count them:

len(keyword.kwlist)
35

There are 35 reserved keywords. There are also soft keywords, which have a special meaning only in specific contexts.

You do not need to memorize every keyword. You will become familiar with them naturally as you write more Python code.

PEP 8 naming: snake_case

Besides the actual naming rules, Python also has conventions for how names should be written. Remember PEP 8, Python's style guide? It also recommends how to write variable names.

For variable names, the general convention is lowercase letters, with underscores separating the words. For example:

  • delivery_fee
  • total_price
  • customer_name

This naming style is called snake_case.

Python does not force you to follow this convention. You could write DeliveryFee, and Python would accept it as a name. But following PEP 8 makes your code easier for other Python developers to read, and it helps keep your own code consistent too. So it is worth getting into the habit of using snake_case right from the beginning.

05Recap and challenge

Let's come back to the one line we started with:

total = 24.75

You can now trace what it does. Python evaluates the right-hand side and creates a float object, with a type, a value and an identity. Then it binds the name total to that object in a namespace. A second assignment such as previous_total = total binds another name to the same object, and id() or is shows you that. Assigning a new value rebinds a name to a different object and leaves the old object, and every other name, alone. You can assign several names at once with multiple assignment, give several names one value with chained assignment, and swap two variables with a, b = b, a. And you can choose a valid name, one that uses letters, digits and underscores, does not start with a digit and is not a keyword, written in snake_case.

Your challenge

Here is a small challenge you can draw for yourself, with names on one side and objects on the other. Write these two statements:

a = b = 0
a = 1

Before running anything else, predict what happens to b. Will it become 1 as well, or will it stay at 0? And more importantly, why?

If you can explain what happens here, you have understood one of the most important ideas behind variables in Python.

In the next lesson you will explore the different types of objects Python supports: integers, floats, strings, Booleans, and more.