Python’s Formatting Styles

So keep in mind that while this article will try to stay objective throughout, there is a very-opinionated world out there when it comes to code. Let’s start with the most opinionated topic: formatting styles.

Formatting Styles
Ok now, yes. The age-old question: spaces or tabs? Regardless of your personal view on how to represent whitespace, its safe to assume that you at least want consistency in code. A style guide serves the purpose of defining a consistent way to write your code. Typically this is all cosmetic, meaning it doesn’t change the logical outcome of the code. Although, some stylistic choices do avoid common logical mistakes.

Style guides serve to help facilitate the goal of making code easy to read, maintain, and extend. As far as Python goes, there is a well-accepted standard. It was written, in part, by the author of the Python programming language itself. PEP 8 provides coding conventions for Python code. It’s fairly common for Python code to follow this style guide.

But let’s be real here: who has time to read through all those guidelines? I mean, sure, you could spend hours reading about how many spaces should go between your parentheses and the opening of a function call or whether you should use single quotes or double quotes for strings (spoiler alert: it doesn’t matter). Or you could just follow these simple rules that will make your code look like a pro wrote it.

1. Use 4-space indentation, and no tabs. This is the most important rule of all. Tabs introduce confusion, and are best left out. 4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read).

2. Wrap lines so that they don’t exceed 79 characters. This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.

3. Use single quotes for strings unless you need to escape a character inside the string (e.g., `’\n’`). Double quotes are fine too, but they can be confusing when used in conjunction with backslashes.

4. Don’t use spaces around operators or after commas. This makes your code look cleaner and more concise. For example:



# First, we import the necessary libraries or modules. In this case, we don't need any.
import random

# Next, we define a function called "print_message" that takes in a message as a parameter and prints it.
def print_message(message):
    print(message)

# We then define a variable called "x" and assign it a value of 5.
x = 5

# We also define a variable called "y" and assign it a value of 10.
y = 10

# Now, we use an if-else statement to check if x is greater than y.
if x > y:
    # If x is greater than y, we call the "print_message" function and pass in the message "x is greater than y".
    print_message("x is greater than y")
else:
    # If x is not greater than y, we call the "print_message" function and pass in the message "x is not greater than y".
    print_message("x is not greater than y")

5. Use a blank line to separate logical sections of your code, such as functions or classes. This makes it easier for others (and yourself) to understand the structure of your program.

6. Avoid using unnecessary parentheses around function calls or list comprehensions. For example:

# This script checks the length of a list and performs different actions based on the result.

# Define a list
my_list = [1, 2, 3, 4, 5]

# Check if the length of the list is greater than 0
if len(my_list) > 0:
    # If the length is greater than 0, call the function do_something()
    do_something()
else:
    # If the length is 0, call the function do_other_thing()
    do_other_thing()

7. Use a consistent naming convention for your variables and functions. PEP 8 recommends using lowercase letters with underscores to separate words (e.g., `my_variable`) or camelCase if you prefer (e.g., `myVariable`).

8. Don’t use global variables unless absolutely necessary. They can cause conflicts and make your code harder to understand. If you must use a global variable, at least give it a descriptive name that makes sense in the context of your program.

9. Use comments sparingly but effectively. Comments should explain what your code is doing, not how it’s doing it (unless there’s some tricky logic involved). For example:

# Calculate the sum of all numbers between 1 and n
# Initialize a variable to store the sum
sum = 0
# Use a for loop to iterate through numbers from 1 to n
# Note: range() function excludes the last number, so n+1 is used to include it
for i in range(1, n+1):
    # Add the current number to the sum
    sum += i
# Print the sum
print("The sum is:", sum)

10. Finally, test your code thoroughly before releasing it to the world. This will help you catch any bugs or logical errors that might otherwise go unnoticed. And if someone else finds a bug in your code, be gracious and thank them for bringing it to your attention. After all, we’re all just trying to make Python look good.

SICORPS