Names are for humans
Python accepts almost any variable name, but code is read by people far more often than it is written. Compare:
x = 12 y = 3 z = x * y
price_per_ticket = 12 ticket_count = 3 total_price = price_per_ticket * ticket_count
Both compute 36. Only one explains itself.
The hard rules, which Python enforces:
- Names use letters, digits, and underscores only, and cannot start with a digit
- No spaces (that is why we write
ticket_count, the underscore style Python programmers call snake_case) - Names are case-sensitive:
Scoreandscoreare different variables - Reserved words like
print,if, andwhileshould not be used as names
The soft rule, which professionals enforce: a name should say what the value means, not what type it is or where you got it.
Quiz
Which variable name best follows Python conventions for storing the number of unread emails?
Code exercise · python
Your turn. This program computes the area of a rectangle but the names are terrible. Rewrite it using the names width, height, and area (same values, same output: 40).
Problem
In one word, what is the Python naming style that joins lowercase words with underscores, like total_price?