Chapters
Python114 chapters

BasicsChapter 6 of 114

Variable Names

What Python allows, what it forbids, and what other people expect.

The rules

A name must start with a letter or an underscore, contain only letters, digits and underscores after that, and avoid the words Python has reserved for itself.

Python
user_name = "Ada"
_private = True
count2 = 7
print(user_name, _private, count2)

Output

Ada True 7

These are all errors: 2count starts with a digit, user-name contains a minus sign, and class is reserved.

Case matters

total, Total and TOTAL are three separate names:

Python
value = 1
Value = 2
VALUE = 3
print(value, Value, VALUE)

Output

1 2 3

Relying on that is a good way to confuse everyone, including yourself.

Reserved words

Thirty-five words belong to the language and cannot be used as names. You do not need to memorise them — your editor colours them, and Python can list them:

Python
import keyword
print(len(keyword.kwlist))
print(keyword.kwlist[:6])

Output

35
['False', 'None', 'True', 'and', 'as', 'assert']

The convention: snake_case

Python code overwhelmingly uses lowercase words joined by underscores:

Python
first_name = "Grace"
items_in_cart = 3
is_logged_in = True
print(first_name, items_in_cart, is_logged_in)

Output

Grace 3 True

The other conventions you will meet:

StyleUsed forExample
snake_casevariables, functionstotal_price
CapWordsclassesShoppingCart
SCREAMING_SNAKEconstantsMAX_RETRIES
_leading_underscoreinternal, hands off_cache

Names are documentation

A name is read far more often than it is written. d saves four keystrokes once and costs a puzzled reader every time:

Python
days_until_renewal = 14
print(f"Renews in {days_until_renewal} days")

Output

Renews in 14 days

Test yourself

2 questions

Which of these is a legal variable name?

Show the answer

_count2 — A name starts with a letter or underscore, holds only letters, digits and underscores, and is not a reserved word.

Why avoid naming a variable list?

Show the answer

It hides the builtin list for the rest of that scope — It is legal and that is the problem: the real function is gone and the error appears much later.

Next chapter

Multiple Assignment

Assign several names at once, unpack a sequence, and swap without a temporary.