Previous | Tutorial index | Next
To be able to make and use names correctly to identify various items in your Python programs.
In Python, an identifier is the name you give to a programming entity. This includes variables, functions, classes, modules, and packages. Identifiers are how you reference these objects later in your code.
age = 25, age is an identifier that points to the integer object 25 in memory.def calculate():, calculate is an identifier for that function object.First Character Rule:
A-Z or a-z) or an underscore (_).name, _private, var11st_place (Starts with a number), @username (Starts with a special char).Subsequent Character Rule:
!, @, #, $, %, ^, &, *, - (hyphen), or spaces.user_name, total_2026, data2user-name (Hyphen is interpreted as the subtraction operator), total$ (Dollar sign), first name (Space is not allowed).Reserved Keywords Rule:
You cannot use Python's reserved keywords as identifiers. These words have special syntactic meaning to the interpreter.
Full list (as of Python 3.11): False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield.
❌ Invalid: if = 5, for = "loop", class = "Math"
Pro Tip: You can check all keywords in your Python environment by running:
import keyword
print(keyword.kwlist)
Python treats uppercase and lowercase letters as distinctly different characters. Therefore:
total, Total, and TOTAL are three entirely separate variables.résumé = "CV", température = 25).A-Z, a-z, 0-9, and _.Why do we follow conventions? As the Zen of Python states: "Readability counts." Code is read far more often than it is written.
Variables and Functions: Use snake_case. All lowercase, with underscores separating words.
student_name, calculate_average, is_validstudentName (That's CamelCase, reserved for classes), StudentName (Looks like a class).Constants: Use UPPER_CASE. All uppercase letters with underscores.
MAX_SPEED, PI, DEFAULT_TIMEOUTmaxSpeed, pi (makes it look like a regular variable).Classes: Use CamelCase (also known as CapWords). Each word starts with a capital letter, no underscores.
class StudentRecord:, class BankAccount:class student_record: (That's for functions).Private/Internal Names (Advanced Hint): A single leading underscore (_internal) suggests that a variable or method is meant for internal use within a module or class. A double leading underscore (__private) invokes name mangling.
1.6 The "Shadowing" Pitfall (Built-in Names) While not a syntax error, you should never use the names of Python's built-in functions as variable names. This "shadows" them, meaning you lose access to the original function.
list = [1, 2, 3] (Now you cannot use the list() constructor later).print = "Hello" (Now you broke the print() function).my_list or items instead of list.# --- Valid and Recommended Names ---
student_first_name = "Alice" # snake_case for variable
BASE_SALARY = 50000 # UPPER_CASE for constant
is_enrolled = True # Boolean flag, clearly descriptive
def calculate_grade(score): # snake_case for function
return score * 1.1
class StudentProfile: # CamelCase for class
pass
# --- Invalid Names (Uncomment to see SyntaxError) ---
# 1st_student = "Bob" # SyntaxError: invalid decimal literal
# student-name = "Bob" # SyntaxError: cannot assign to expression here
# def = 10 # SyntaxError: invalid syntax (keyword)
# --- Names that are Legal but Dangerous (Shadowing built-ins) ---
# WARNING: DO NOT DO THIS!
# list = [1, 2, 3] # Legal, but now list() is broken.
# print = "Hello" # Legal, but now you can't print!
# The right way to handle that:
my_numbers = [1, 2, 3] # Use a descriptive alternative
# --- Demonstrating Case Sensitivity ---
score = 90
Score = 95
SCORE = 100
print(score) # Outputs: 90
print(Score) # Outputs: 95
print(SCORE) # Outputs: 100
Question 1: Which of the following are syntactically valid variable names in Python? (Select all that apply)
a) _temp_value
b) 2nd_attempt
c) user-id
d) total_amount
e) class
Question 2: Are myVariable and myvariable the same variable? Why?
Question 3: Which of the following names best follows the PEP 8 convention for a constant representing the maximum number of login attempts?
a) maxLoginAttempts
b) MAX_LOGIN_ATTEMPTS
c) max_login_attempts
d) MaxLoginAttempts
Question 4: Why is import a bad name for a variable?
Question 5: (Tricky) Which of the following is valid but considered a terrible practice?
a) _hidden
b) π (Pi symbol)
c) print
d) user_name
Exercise 1: Spot the Invalid Names Identify the invalid names below, explain why they are invalid, and rewrite them correctly using PEP 8 rules:
1st_namelast#namewhileuser agetotal-score_private (Is this invalid? Actually, it's valid. Trick question!)Exercise 2: Refactor (Fix the Mess) A new programmer wrote the following code. The names are legal but violate PEP 8 conventions. Rewrite the code with proper naming conventions.
# Bad Example - Fix it!
studentName = "John"
StudentAge = 20
def getAverageGrade(grade1, grade2):
return (grade1 + grade2) / 2
MAXIMUMGRADE = 100
student_name = "John"
student_age = 20
def get_average_grade(grade1, grade2):
return (grade1 + grade2) / 2
MAXIMUM_GRADE = 100
Exercise 3: Write a Short Program Write a Python program that declares 6 variables to represent a book in a library:
Title (string)
Author (string)
Publication year (integer)
Price (float)
Is available (boolean)
Number of pages (integer)
Make sure all variables follow PEP 8 rules for regular variables.
# Book information variables following PEP 8 snake_case naming
title = "The Pragmatic Programmer"
author = "David Thomas and Andrew Hunt"
publication_year = 1999
price = 45.99
is_available = True
num_pages = 352
# Print the book details
print("Book Details:")
print(f"Title: {title}")
print(f"Author: {author}")
print(f"Publication Year: {publication_year}")
print(f"Price: ${price:.2f}")
print(f"Available: {is_available}")
print(f"Number of Pages: {num_pages}")
Explanation:
snake_case: publication_year, is_available, num_pages.int for year and pages, float for price, bool for availability.Question 1 (Research):
The rule says you cannot use a hyphen (-) in a variable name. Yet, it is a common character. Why do you think Python (and most programming languages) use underscores (_) instead of hyphens for multi-word names? (Hint: Think about the arithmetic operator for subtraction).
Question 2 (Debugging): A student runs the following code:
sum = 5 + 10
print(sum)
sum = sum("Hello") # They try to add up letters later
This code works initially but fails later. Why is using sum as a variable name a bad idea in a large program?
Question 3 (Comprehension): Explain the difference between a syntactic rule (like "cannot start with a number") and a convention (like "use snake_case for variables"). If you break a syntactic rule, what happens? If you break a convention, what happens?
Question 4 (PEP 8 Deep Dive):
Go to the official PEP 8 documentation online (or a summary) and find the section on "Naming Conventions". Name one type of identifier (e.g., Class, Function, Constant) and write down the specific PEP 8 recommendation for it. Why does PEP 8 specifically recommend CamelCase for classes but snake_case for functions?
PEP 8 Recommendation for One Identifier Type
Classes: According to PEP 8, "Class names should normally use the CapWords convention". This is also known as CamelCase or PascalCase, where each word starts with a capital letter and no underscores are used (e.g., class CustomerOrder:, class FileManager:).
(Other valid answers could include:
MAX_CONNECTIONS = 100)Why Classes Use CamelCase and Functions Use snake_case
PEP 8 recommends this distinction for several key reasons:
Visual distinction and instant recognition: Using different conventions for different types of identifiers makes it immediately clear what kind of entity you are dealing with. When you see CamelCase, you know it's a class; when you see snake_case, you know it's a function or variable. This visual cue helps developers quickly understand the code structure.
Historical consistency and community standards: Python's standard library has long used these conventions, and maintaining consistency across the ecosystem makes code more readable and predictable for all Python developers.
Different semantic roles: Classes and functions serve fundamentally different purposes in Python. Classes are blueprints for creating objects and often represent nouns (e.g., Customer, Order), while functions perform actions and represent verbs (e.g., calculate_total(), get_user_info()). Using different naming styles reinforces this semantic distinction.
Avoiding ambiguity: If both classes and functions used the same naming convention, it would be harder to distinguish at a glance whether MyClass() is being instantiated or my_function() is being called. The visual difference helps prevent confusion, especially in large codebases.
As PEP 8 itself emphasizes, "Readability counts", and these naming conventions are designed to make Python code as clear and maintainable as possible.