Python tutorials · Part 1 of 8

Variables, keywords and identifiers in Python

An identifier is the name you give a variable, function or class. Python has strict rules for what a valid name looks like, and a short list of keywords you can't use. Here's all of it, with examples.

Every program needs to remember things: a price, a list of names, a trained model. In Python you remember a value by giving it a name. That name is called an identifier, and the pairing of a name with a value is what we usually call a variable.

What is a variable in Python?

You create a variable with the assignment operator =:

price = 250
city = "Pune"
in_stock = True

print(price, city, in_stock)
250 Pune True

Read price = 250 as "make the name price refer to the value 250", not as maths-style equality. There's no separate declaration step and no type to state: Python works out that 250 is an integer and "Pune" is a string.

Names point to objects

In Python, a variable is a label stuck on an object, not a box that holds a value. That difference becomes visible with lists:

a = [1, 2, 3]
b = a          # b now refers to the same list
b.append(4)
print(a)
[1, 2, 3, 4]

b = a didn't copy the list. It attached a second label to the same list, so changing it through b is visible through a. If you want a separate list, copy it explicitly with a.copy() or list(a).

Reassigning a name simply moves the label:

x = 10
x = x + 5
print(x)
15

You can also assign several names at once, which is handy for swapping:

low, high = 3, 9
low, high = high, low
print(low, high)
9 3

What is an identifier in Python?

An identifier is any name you create: a variable, function, class or module name. Python's rules for a valid identifier are short:

  1. It can contain letters, digits and underscores (_).
  2. It cannot start with a digit.
  3. It cannot contain spaces or symbols like -, @ or $.
  4. It cannot be a keyword (see below).
  5. It is case-sensitive: score, Score and SCORE are three different names.

Valid: total, user_name, _cache, model2, learningRate. Invalid: 2model (starts with a digit), user-name (hyphen), my score (space), class (keyword).

Python can check a name for you:

print("user_name".isidentifier())
print("2model".isidentifier())
print("user-name".isidentifier())
True
False
False

isidentifier() checks the spelling rules only; it doesn't know about keywords. "class".isidentifier() returns True, even though you can't use it as a name.

Python keywords

Keywords are words reserved by the language itself, like if, for, def and return. You can't use them as identifiers. Python lists them in the keyword module:

import keyword

print(len(keyword.kwlist))
print(keyword.iskeyword("class"), keyword.iskeyword("klass"))
35
True False

The 35 keywords in current Python 3 are:

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.

There are also a few soft keywords (match, case, _ and type) that act as keywords only in specific statements, so they're still allowed as ordinary names elsewhere.

Using a keyword as a name is a syntax error before your code even runs:

class = "A"
      ^
SyntaxError: invalid syntax

Don't shadow built-in names

Names like list, str, sum, max and input are not keywords, so Python lets you reuse them, and that's a trap:

values = [3, 7, 2]
print(max(values))
7

If you had written max = 10 earlier in the program, the call max(values) would fail with TypeError: 'int' object is not callable, because the name max now points at an integer. Avoid naming variables after built-ins; max_value, items or total are clearer anyway.

Naming conventions (PEP 8)

The rules say what's allowed; the conventions say what's expected. Python's style guide, PEP 8, recommends:

  • snake_case for variables and functions: learning_rate, load_data().
  • PascalCase for classes: LinearModel.
  • UPPER_CASE for constants: MAX_EPOCHS = 50.
  • A leading underscore for internal helpers: _normalise().
  • Descriptive names over short ones: n_samples beats n, except for tiny loop counters like i.

Good names make code read like a sentence. Compare t = p * q with total = price * quantity.

Dynamic typing

Python names don't have types; the objects they point to do. The same name can refer to different types over time:

value = 42
print(type(value).__name__)
value = "forty-two"
print(type(value).__name__)
int
str

This flexibility is convenient, but reusing one name for different kinds of data makes code harder to follow. Keep one meaning per name.

Common mistakes

  • Using a name before assigning it, which raises NameError: name 'x' is not defined. Check spelling and case: Total and total are different.
  • Confusing = and ==. = assigns; == compares.
  • Expecting b = a to copy a list or dictionary. It doesn't; both names point to the same object.
  • Shadowing built-ins such as list, dict, sum or id.
  • Hyphens in names. learning-rate is read as learning minus rate.

Practice

  1. Which of these are valid identifiers: _temp, 3d_plot, plot3d, for, user name?
  2. Swap the values of a = "left" and b = "right" in one line.
  3. Predict the output: x = [1]; y = x; y = y + [2]; print(x).

Answers

import keyword

for name in ["_temp", "3d_plot", "plot3d", "for", "user name"]:
    print(name, name.isidentifier() and not keyword.iskeyword(name))

a, b = "left", "right"
a, b = b, a
print(a, b)

x = [1]; y = x; y = y + [2]; print(x)
_temp True
3d_plot False
plot3d True
for False
user name False
right left
[1]

The last one prints [1] because y + [2] builds a new list and rebinds y to it; x still points to the original. (y.append(2) would have changed both.)

Where this shows up in machine learning

ML code is full of names that carry meaning by convention: X for the feature matrix and y for the target, X_train and X_test for the splits, model, n_estimators, learning_rate. scikit-learn even uses a trailing underscore, such as coef_, to mark values learned during training. And the "names point to objects" rule explains a classic data bug: modifying a DataFrame you thought was a copy, and silently changing the original.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.