Previous | Tutorial index | Next

Tutorial 1: Naming Rules and Conventions in Python

Learning Objective

To be able to make and use names correctly to identify various items in your Python programs.

1. Introduction

1.1 What are Identifiers?

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.

1.2 The Three Golden Rules (Syntactic Rules – Must Follow or SyntaxError)

  1. First Character Rule:

  2. Subsequent Character Rule:

  3. Reserved Keywords Rule:

1.3 Case Sensitivity (The Tricky Detail)

Python treats uppercase and lowercase letters as distinctly different characters. Therefore:

1.4 Unicode and Non-ASCII Characters (The Subtle Exception)

1.5 PEP 8 Naming Conventions (Best Practices – Not Enforced, but Crucial)

Why do we follow conventions? As the Zen of Python states: "Readability counts." Code is read far more often than it is written.

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.

2. Code Examples (Annotated)

# --- 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

3. Quiz (Check Your Understanding)

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

Answer Valid: a) `_temp_value` and d) `total_amount`. b) starts with a digit; c) contains a hyphen (subtraction operator); e) is a reserved keyword.

Question 2: Are myVariable and myvariable the same variable? Why?

Answer No. Python is case‑sensitive, so `myVariable` and `myvariable` are two distinct identifiers.

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

Answer b) `MAX_LOGIN_ATTEMPTS` – constants should be in `UPPER_CASE` with underscores.

Question 4: Why is import a bad name for a variable?

Answer `import` is a reserved keyword in Python. Using it as a variable name causes a `SyntaxError`.

Question 5: (Tricky) Which of the following is valid but considered a terrible practice? a) _hidden b) π (Pi symbol) c) print d) user_name

Answer c) `print` – while syntactically valid, it shadows the built‑in `print()` function and breaks its normal use.

4. Exercises (In-Class / Lab Practice)

Exercise 1: Spot the Invalid Names Identify the invalid names below, explain why they are invalid, and rewrite them correctly using PEP 8 rules:

  1. 1st_name
  2. last#name
  3. while
  4. user age
  5. total-score
  6. _private (Is this invalid? Actually, it's valid. Trick question!)
Sample Solution 1. Invalid: starts with a digit → `first_name` 2. Invalid: contains `#` → `last_name` 3. Invalid: `while` is a keyword → `loop_condition` (or similar) 4. Invalid: contains a space → `user_age` 5. Invalid: contains `-` (subtraction) → `total_score` 6. Valid – it’s a convention for internal names, but syntactically correct.

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
Sample Solution
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:

Make sure all variables follow PEP 8 rules for regular variables.

Sample Answer
# 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:

5. Homework Questions (Deep Thinking)

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).

Sample Answer Hyphens are already used as the subtraction operator. If `my-variable` were allowed, the interpreter would interpret it as `my` minus `variable`, causing ambiguity and errors. Underscores are not operators, so they are safe and visually clear for separating words.

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?

Sample Answer `sum` is a built‑in function. By reassigning it to a variable, the student shadows the original `sum()` function. Later, when they try to call `sum()` on a string, they get a `TypeError` because `sum` is now an integer, not a function. This leads to confusing bugs and breaks code that relies on the built‑in.

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?

Sample Answer A syntactic rule is enforced by the Python interpreter; breaking it causes a `SyntaxError` and the program will not run. A convention is a guideline recommended by PEP 8 for readability and consistency; breaking it does not produce an error, but it makes the code harder to read and maintain, and may confuse other programmers.

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?

Sample Answer

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:

Why Classes Use CamelCase and Functions Use snake_case

PEP 8 recommends this distinction for several key reasons:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

6. Summary Checklist (For Student Self-Review)

Previous | Tutorial index | Next