7 Code style
To make your programs easier to read and understand, both for yourself (especially when revisiting your code later) and for others, follow these guidelines:
Organize your code into reusable blocks, such as functions.
Use short but descriptive names for functions, parameters, and variables, following the snake_case style.
# Bad N, temp, currentScore # Good student_count, temperature, current_scoreSeparate functions with two empty lines.
def add(a, b): return a + b def multiply(a, b): return a * bOptionally, use a single empty line to separate larger parts of the code.
Document your code using comments (
#) and docstrings:def calculate_area(radius): """ Calculate the area of a circle given its radius. Parameters: radius (float): The radius of the circle. Returns: float: The area of the circle. """ return np.pi * radius**2Always use 4 spaces per indentation level.
# Bad indentation for i in range(10): print(i) if i % 2 == 0: print("Even number") # Good indentation for i in range(10): print(i) if i % 2 == 0: print("Even number")Tip: In Jupyter notebooks (and many other Python editors), pressing Tab inserts 4 spaces automatically.
Avoid overly long lines. Python’s style guide (PEP 8) suggests a maximum of 79 characters per line.
Follow the Whitespace in Expressions and Statements section of PEP 8. A few examples:
# Bad result=3+4*5 # Good result = 3 + 4 * 5# Bad: no spaces after commas numbers = [1,2,3,4,5] names = ["Alice","Bob","Charlie"] # Good: spaces after commas improve readability numbers = [1, 2, 3, 4, 5] names = ["Alice", "Bob", "Charlie"]# Bad: cramped keywords if(a>0 and a<10): print("It is between 1 and 9") while(i<5): print(i) # Good: spaces improve readability if a > 0 and a < 10: print("It is between 1 and 9") while i < 5: print(i)# Bad: no spaces after commas, a space after the function name def greet(name,age): print (f"Hello {name}, you are {age} years old") # Good: space after commas, no space after the function name def greet(name, age): print(f"Hello {name}, you are {age} years old")Use tools such as Pylint and Black to check or fix code that violates PEP 8.