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
| What | Style | Example |
|---|---|---|
| variable | snake_case | total_price |
| function | snake_case | calculate_total() |
| constant | UPPER_CASE | MAX_LIVES |
| class | PascalCase | BankAccount |
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.
def calculate_area(length, width):
return length * width
room_area = calculate_area(4, 5)
print(room_area)20
Read it out loud: "room area is calculate area of 4 and 5". The names tell the story.
Avoid other languages' styles
def CalculateArea(L, W):
return L * W
roomArea = CalculateArea(4, 5)
print(roomArea)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.