Python Best Practices are guidelines for writing clean, maintainable, and efficient code.
đ PEP 8 Style Guide:
⢠4 spaces for indentation
⢠Max line length: 79 characters
⢠snake_case for variables
⢠PascalCase for classes
⨠Best Practices:
⢠Use meaningful variable names
⢠Write docstrings
⢠Don't repeat yourself (DRY)
⢠Keep functions small and focused
⢠Use list comprehensions
⢠Handle exceptions properly
⢠Use virtual environments
â ď¸ Common Pitfalls:
⢠Mutable default arguments
⢠Not closing files
⢠Comparing with == for None
⢠Using global variables
python
# Good practices example
def calculate_tax(income, tax_rate=0.2):
"""
Calculate tax based on income and tax rate.
Args:
income (float): Annual income
tax_rate (float): Tax rate (default: 0.2)
Returns:
float: Tax amount
"""
if income < 0:
raise ValueError("Income cannot be negative")
return income * tax_rate
# Use 'is' for None comparison
value = None
if value is None:
print("Value is None")
# List comprehension instead of loops
squares = [x**2 for x in range(10)]
print(f"Tax: {calculate_tax(50000)}")You should see
Value is None Tax: 10000.0