Basic Rules of Python
Python, like any programming language, has a set of rules and conventions that developers should follow to write clean, readable, and maintainable code.
Here are some basic rules and guidelines for Python:
{}
as in some other languages).# Good
if x > 0:
print("Positive number")
# Bad (using tabs)
if x > 0:
\tprint("Positive number")
# Good
def add_numbers(a, b):
return a + b
# Bad (missing spaces)
def add_numbers(a,b):
return a+b
# Good
result = x + y # Adding x and y
# Bad (redundant comment)
result = x + y # Add x and y to get the result
# Good
def calculate_average(numbers_list):
total = sum(numbers_list)
count = len(numbers_list)
return total / count
# Bad (non-descriptive names)
def avg(nums):
t = sum(nums)
c = len(nums)
return t / c
# Good
message = "Hello, World!"
# Bad (mixing quotes)
message = 'Hello, World!'
# Good
import math
import os
# Bad (multiple imports on one line)
import math, os
# Good
def calculate_total(price, tax_rate=0.1):
return price + (price * tax_rate)
# Bad (default argument not at the end)
def calculate_total(tax_rate=0.1, price):
return price + (price * tax_rate)
# Good
def process_items(items=None):
if items is None:
items = []
# rest of the function
# Bad (using a mutable default argument)
def process_items(items=[]):
# rest of the function
try
, except
, and other relevant clauses.# Good
try:
result = x / y
except ZeroDivisionError:
result = float('inf')
# Bad (too broad exception handling)
try:
result = x / y
except Exception:
result = None
These basic rules contribute to writing clean and readable Python code. Adhering to these conventions helps make your code consistent and easy to understand for both yourself and other developers.
Thank you,