Python naming standards for Beginners
Cheat sheet covers print, concatenation, list, tuples, if-elif-else statements, dictionaries, user input, while loops, classes, files I/O, functions, exceptions etc..
1. Variables
- Use snake_case for variable names: words are lowercase and separated by underscores.
- Avoid single-letter names except in loops or temporary, throwaway variables.
student_name = "Alice"
total_score = 95
2. Functions
- Use snake_case for function names.
- Name functions based on their purpose, using descriptive verbs or phrases.
def calculate_area(radius):
return 3.14 * radius ** 2
3. Constants
- Use ALL_CAPS for constants, with words separated by underscores.
- Place constants at the beginning of a file or module.
PI = 3.14159
MAX_CONNECTIONS = 100
4. Classes
- Use PascalCase (capitalize each word without underscores).
- Class names should be nouns that describe objects.
class Circle:
pass
5. Modules and Packages
- Use lowercase for module and package names.
- Use underscores sparingly in module names (e.g., my_module), and avoid them in package names unless needed for clarity.
my_module.py
6. Instance and Class Attributes
- Use snake_case for attribute names.
- Private attributes (for internal use only) should start with a single underscore (_), while strongly private attributes (meant to prevent subclass access) start with two underscores (__).
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
self._area_cache = None
7. Method Names
- Use snake_case for method names.
- Follow the same rules as functions, but methods inside a class often relate specifically to that class’s behavior.
class Shape:
def calculate_area(self):
pass
8. Naming Conventions for Special Methods
- Special methods that start and end with double underscores are known as “dunder” (double underscore) methods, like __init__ for initialization.
- These should be used as-is and never modified for regular functions.
class Person:
def __init__(self, name):
self.name = name
9. Avoid Reserved Words
- Python has reserved words that cannot be used as identifiers (e.g., class, def, if, else, etc.).
# Avoid using reserved keywords
class_ = "Math" # Instead of class