livepython.net
CHAPTER 04Variables
4.2  NAMING RULES

Python Variable Naming Rules (With Examples)

Letters, Numbers and Underscores Only

Python has a few rules for variable names. Break one, and Python stops with an error before running anything. The first rule: a name may only use

  • letters: a to z and A to Z,
  • numbers: 0 to 9,
  • the underscore: _.
PYTHONedit me
user_name = "Sunny"
score2 = 88
print(user_name, score2)
OUTPUT
Sunny 88

No spaces, no symbols

A space, a hyphen - or symbols like @ and ! are not allowed:

PYTHONedit me
user-name = "Sunny"
OUTPUT
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?

Python reads user-name as "user minus name", a calculation, and you can't store a value into a calculation. A space is just as bad: Python sees two separate names.

Use the underscore instead

When a name has several words, join them with _:

Not allowedAllowed
first namefirst_name
user-nameuser_name
total$total_dollars

Think of the underscore as the space bar for names. It keeps the words readable, and Python accepts it.

Names use only letters, numbers and underscores. Join words with _.

your turnPick the right idea

Which name is allowed?

Think about it, then pick one.
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Start with a Letter or an Underscore

The second rule: a name must start with a letter or an underscore. It can't start with a number.

PYTHONedit me
player1 = "Sunny"
_secret = "Rocky"
print(player1, _secret)
OUTPUT
Sunny Rocky

Numbers are fine inside or at the end of a name, like player1 or level_2. Just not at the start:

PYTHONedit me
2name = "Sunny"
OUTPUT
SyntaxError: invalid decimal literal

Why?

When Python sees a digit first, it expects a number, like 2 or 2.5. Then it finds letters right after it and gets confused: 2name isn't a valid number. The message "invalid decimal literal" means exactly that: "this doesn't look like a proper number".

What about the underscore?

Starting with _ is allowed. Programmers often use a leading underscore to mean "this is for inside use only". As a beginner, you rarely need it. Start your names with a letter.

Not allowedAllowed
1st_placefirst_place
2namename2
9liveslives_9

A name starts with a letter (or _), never with a number.

your turnPick the right idea

Which name is NOT allowed?

Think about it, then pick one.

Capital Letters Make a Different Name

Python is case-sensitive: it treats capital and small letters as different. So age, Age and AGE are three different variables:

PYTHONedit me
age = 25
Age = 30
print(age)
print(Age)
OUTPUT
25
30

Each one is its own box with its own value. You remember this from chapter 2: print works, but Print doesn't.

Where this causes bugs

The most common mistake is creating a variable with one spelling and using it with another:

PYTHONedit me
name = "Sunny"
print(Name)
OUTPUT
NameError: name 'Name' is not defined

Python looks for Name with a capital N. It only knows name with a small n, so it stops. To Python, these are just different names.

Keep it simple

  • Write variable names in small letters, like name, score, total_price. That's the Python habit, and you'll see why in the last lesson of this topic.
  • When you get a NameError, compare the spelling and the capital letters with the line where you created the variable.

Think of it like a password: Sunny123 and sunny123 look almost the same to you, but the computer treats them as completely different.

age and Age are different names. Keep yours in small letters, and spell them the same every time.

your turnPredict the output

What will this print?

score = 10 Score = 20 print(score)
Your turn! What will this code show on the screen?

Don't Use Python Keywords

Python has a few words that already have a special job, called keywords. You can't use them as variable names:

PYTHONedit me
class = "5B"
OUTPUT
SyntaxError: invalid syntax

class is a keyword (you'll meet it in the last chapter), so Python refuses to store anything in it.

The Python keywords

FalseNoneTrueandas
assertasyncawaitbreakclass
continuedefdelelifelse
exceptfinallyforfromglobal
ifimportinislambda
nonlocalnotorpassraise
returntrywhilewithyield

You don't need to memorise them. Code editors colour keywords differently, so you'll notice when you type one. And by the end of this course, you'll know what most of them do.

Also avoid built-in names

print is not a keyword, so Python lets you use it as a name. But then you lose the print() function:

PYTHONedit me
print = 5
print("Hello")
OUTPUT
TypeError: 'int' object is not callable

Now print is just the number 5, and you can't "call" a number. Avoid the names of functions you use, like print, type and input.

Keywords and built-in function names already have a job. Pick another name.

your turnFix the code

Fix the name so the code prints 5B

It should print: 5B

class = "5B"
print(class)
This code does not work yet. Fix it, then press Run.
your turnType the output

Type what this prints

print("A", "B", sep="")
Read the code line by line, then type the output exactly.

Choosing Good Variable Names

The rules tell you which names Python accepts. Good habits tell you which names people can read. Python doesn't force these, but every good programmer follows them.

1. Say what it stores

PYTHONedit me
x = "Sunny"
d = 78
student_name = "Sunny"
total_score = 78
OUTPUT

x and d could mean anything. student_name and total_score explain themselves. Ask yourself: "Would someone else understand this name without reading the rest of the code?"

2. Use snake_case

There are three common ways to join words in a name:

StyleExampleUsed for
snake_caseuser_namevariables in Python
camelCaseuserNamevariables in JavaScript
PascalCaseUserNameclass names (you'll meet them later)

In Python, variables use snake_case: small letters, words joined by _. It's what the official Python style guide, called PEP 8, recommends, so most Python code you'll ever read looks like this.

3. Not too short, not too long

n is too short, and the_total_number_of_students_in_the_class is too long. student_count is just right.

StoresGood names
a nameplayer_name, city
a countitem_count, lives
a priceprice, total_cost

Good names say what they store, in snake_case.

your turnPick the right idea

Which is the best name for a product's price?

Think about it, then pick one.

Practice: Naming rules

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 18.Python Program to Show That Variable Names Are Case-SensitiveEasySolve
  2. 33.Fix the Invalid Variable Names in a Python ProgramEasySolve