Python Style Guide (PEP 8)

beginner
20 min

Python Style Guide (PEP 8)

Welcome to CodeYourCraft's Python Style Guide tutorial! Today, we'll be diving into PEP 8, a set of guidelines to write clear and readable Python code. Let's get started!

Why PEP 8? 🎯

PEP 8 is the official style guide for Python and is widely followed by the Python community. It helps maintain consistency and makes your code easier to read and understand.

Python Naming Conventions 📝

Naming conventions are essential for writing readable code. Here are some common naming conventions in Python:

  • Variable names: lowercase with words separated by underscores (snake_case)
  • Function names: lowercase with words separated by underscores or a single word (snake_case or lowercase)
  • Class names: Capitalize the first letter of each word (CamelCase)

Code Layout 💡

Proper code layout enhances readability. Here are some tips for organizing your code:

  • Use four spaces for indentation (not tabs)
  • Maximum line length is 79 characters
  • Blank lines can be used to separate functions, classes, or sections of code

Imports 📝

Import statements should be placed at the top of the file, in alphabetical order, and separated by a blank line.

python
import os import sys from my_module import MyClass

Docstrings 💡

Docstrings provide documentation for functions, classes, and modules. They should follow this format:

python
def my_function(): """ This is a brief description of my_function. Parameters: - arg1 (int): Description of arg1 - arg2 (str): Description of arg2 Returns: - result (int): Description of the function's result """

Comments 📝

Comments are useful for explaining complex parts of your code or providing temporary notes. In Python, you can use the hash symbol (#) to create comments:

python
# This is a comment

Quiz

Quick Quiz
Question 1 of 1

What is the maximum line length in Python according to PEP 8?

Practice

Now, let's put these concepts into practice! Write a Python function using PEP 8 conventions:

python
def greet(name, message="Hello"): """ Greets the user with a custom message. Parameters: - name (str): The user's name - message (str, optional): The greeting message Returns: - greeting (str): The greeting for the user """ greeting = message + ", " + name + "!" return greeting

Happy coding! 💡