livepython.net
CHAPTER 16Styling Your Code (PEP 8)
16.2  NAMING

Python Naming Conventions: snake_case, UPPER_CASE and More

snake_case for Variables and Functions

Naming conventions are the agreed ways to write names. In Python, variables and functions use snake_case: small letters, with words joined by an underscore _. You met it in chapter 4. PEP 8 uses it for functions too.

Think of it like the labels in a well-run kitchen: every jar is labelled the same way, in the same place, so anyone can find the sugar.

The four naming styles of PEP 8

WhatStyleExample
variablesnake_casetotal_price
functionsnake_casecalculate_total()
constantUPPER_CASEMAX_LIVES
classPascalCaseBankAccount

This topic has one lesson for each. First, snake_case.

Variables are things, functions are actions

  • A variable holds a thing, so give it a noun: room_area, player_name.
  • A function does something, so start its name with a verb: calculate_area, print_report, get_average.
  • A list holds many things, so use a plural: names, prices.
PYTHONedit me
def calculate_area(length, width):
    return length * width


room_area = calculate_area(4, 5)
print(room_area)
OUTPUT
20

Read it out loud: "room area is calculate area of 4 and 5". The names tell the story.

Avoid other languages' styles

PYTHONedit me
def CalculateArea(L, W):
    return L * W


roomArea = CalculateArea(4, 5)
print(roomArea)
OUTPUT
20

Python runs it, but it looks like Java or JavaScript code. CalculateArea looks like a class (PascalCase), roomArea is camelCase, and L and W say very little. A Python reader trips over every name.

Variables and functions use snake_case: nouns for variables, verbs for functions.

your turnPick the right idea

Which is a PEP 8 function name?

Think about it, then pick one.
your turnFill the gap

Call the function by its name

def calculate_total(price, qty): return price * qty print(?(20, 3))

It should print: 60

Which piece makes this code work?

UPPER_CASE for Constants

A constant is a value that should never change while the program runs: the number of days in a week, a tax rate, the most lives a player can have. PEP 8 writes constants in UPPER_CASE: capital letters, with words joined by _.

Think of it like the speed limit printed on a road sign. Cars change speed all the time, but the number on the sign stays the same.

PYTHONedit me
MAX_LIVES = 3
TAX_RATE = 0.18

lives = MAX_LIVES
lives -= 1
print("Lives left:", lives)
print("Tax on 500:", 500 * TAX_RATE)
OUTPUT
Lives left: 2
Tax on 500: 90.0

lives changes during the game, so it's a normal variable. MAX_LIVES never changes, so it's a constant.

The rules

  • Write constants in UPPER_CASE: MAX_LIVES, PASS_MARK, DAYS_IN_WEEK.
  • Put them at the top of the program, before your functions, so they're easy to find and change.
  • Give them a clear name. MAX_LIVES is good. M is not.
  • A value that changes, like a score or a running total, is a normal variable in snake_case.

Common beginner doubt

"So Python protects constants from changes?" No! Python has no real constants. The capital letters are a promise to the reader, not a lock:

PYTHONedit me
MAX_LIVES = 3
MAX_LIVES = 5
print(MAX_LIVES)
OUTPUT
5

Python happily changes it. That's why the naming matters: when every programmer sees MAX_LIVES, they know "don't change this", and they don't.

UPPER_CASE says "this value never changes". Python won't stop you, so keep the promise.

your turnPredict the output

What will this print?

PASS_MARK = 40 PASS_MARK = 35 print(PASS_MARK)
Your turn! What will this code show on the screen?
your turnPick the right idea

Which value should be an UPPER_CASE constant?

Think about it, then pick one.

PascalCase for Classes: A First Look

A class is a blueprint for making your own kind of value, like a Student or a BankAccount. You'll learn to write classes in chapter 20. For now, you only need their naming style: PascalCase, where every word starts with a capital letter and there are no underscores.

Think of it like the names of shops on a street: "Sunny Bakery", "Rocky Sports". Each word starts with a capital, and you can tell at a glance that it's a name of something special.

StyleLooks likeUsed for
PascalCaseShoppingCartclasses
snake_caseshopping_cartvariables and functions
UPPER_CASESHOPPING_CARTconstants

You've already met PascalCase

Every error name you've seen in this course is a class, written in PascalCase:

PYTHONedit me
print(int("abc"))
OUTPUT
ValueError: invalid literal for int() with base 10: 'abc'

ValueError, NameError, TypeError, IndentationError: every word starts with a capital, with no _ between the words. So when you read Python code and see a name like that, you can guess "that's probably a class".

The rules

  • Classes: PascalCase, like Student, BankAccount, GameLevel.
  • Never use PascalCase for a variable or a function. Readers would think it's a class.
  • Python's oldest basic types, like int, str and list, are small letters. They're older than the rule, so they're the exception.

Names to avoid everywhere

PEP 8 says: never use a lowercase l, a capital O or a capital I as a one-letter name. In many fonts they look like the numbers 1 and 0:

PYTHONedit me
l = 1
O = 0
print(l + O)
OUTPUT
1

Is that "one plus zero" or "l plus O"? A reader can't tell. Use a real word instead.

Classes use PascalCase. If you see capitals in a name, think "class".

your turnPick the right idea

Which name is written in PascalCase, for a class?

Think about it, then pick one.
your turnType the output

Remember dictionaries?

scores = {"Sunny": 90, "Lucky": 75} print(scores.get("Rocky", 0))
Read the code line by line, then type the output exactly.

Clear Names and Names to Avoid

A clear name tells the reader what a value is, without making them read the rest of the code. Picking good names is the cheapest way to make your code easier to read.

Think of it like labelling moving boxes. "Kitchen: plates" tells you everything. "Box 7" makes you open it to find out.

The rules

HoldsAvoidBetter
a countnstudent_count
a listdataprices (plural)
one item from a listxprice (singular)
True or Falseflagis_open, has_ticket
  • A True/False value reads like a yes-or-no question: is_open, has_ticket, can_vote.
  • Loop over a plural, name the item in the singular: for price in prices:.
  • One letter is fine only for a tiny loop counter, like i in range().
PYTHONedit me
prices = [120, 80, 45]
is_member = True
total = 0
for price in prices:
    total += price
if is_member:
    total -= 20
print("To pay:", total)
OUTPUT
To pay: 225

Don't reuse built-in names

max, sum, list, str and input aren't keywords, so Python lets you use them as names. But then you lose the function:

PYTHONedit me
max = 100
marks = [72, 95, 88]
print(max(marks))
OUTPUT
TypeError: 'int' object is not callable

Don't be scared of this error! It's saying: "max is the number 100 now, and you can't call a number like a function." You met the same problem with print in chapter 4. Pick a name that says more, like full_marks.

Common beginner doubt: "Aren't long names slower to type?" A little. But you read each name many more times than you type it, and your code editor fills names in for you after a few letters.

Name values for what they mean, and never reuse a built-in function's name.

your turnFix the code

Fix the code so it prints both lines

It should print: Best: 75 Allowed tries: 3

max = 3
scores = [40, 75, 62]
print("Best:", max(scores))
print("Allowed tries:", max)
This code does not work yet. Fix it, then press Run.
your turnPick the right idea

Which name is best for a value that says whether the shop is open?

Think about it, then pick one.

Practice: Naming

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

  1. 142.Python Program to Rename Unclear VariablesEasySolve
  2. 143.Fix a Variable That Hides a Python Built-in FunctionEasySolve
  3. 144.Python Program to Rename Functions and Constants in PEP 8 StyleMediumSolve