Built with Tutify.io

    AIStudyLabs

    Python Syntax Rules and Style (PEP 8)

    Python Syntax Rules and Style (PEP 8)

    Introduction

    In this lesson, you will learn how to write clean, consistent, and professional Python code by following Python’s syntax rules and the official style guide, PEP 8. You already know how to run Python code; now you’ll focus on how that code should look so it’s easy for you and others to read, understand, and maintain.

    We will cover:


    1. Python Syntax Rules: Variables, Keywords, Basic Statements

    1.1 Variables and Identifiers

    In Python, variable names (identifiers):

    # Valid variable names
    user_name = "alice"
    user_age = 30
    _pi_approx = 3.14
    
    # Invalid examples (will cause SyntaxError if you try to use them)
    # 2user = "bob"       # cannot start with a digit
    # for = 10            # 'for' is a keyword
    
    # Output
    # (No output; this code simply defines variables without errors.)
    

    1.2 Keywords and Basic Statements

    You can’t use Python keywords as variable names. Some common ones: if, else, for, while, def, class, return, import, True, False, None.

    Basic statements follow clear syntax rules:

    is_logged_in = True
    
    if is_logged_in:
        welcome_message = "Welcome back!"
    else:
        welcome_message = "Please log in."
    
    print(welcome_message)
    
    # Output
    Welcome back!
    

    2. Indentation and Spacing for Readable Code

    2.1 Indentation Rules

    Python uses indentation to define code blocks (no braces {} like some other languages).

    PEP 8 strongly recommends:

    # Correct indentation (4 spaces)
    score = 85
    
    if score >= 90:
        grade = "A"
    elif score >= 80:
        grade = "B"
    else:
        grade = "C or below"
    
    print("Grade:", grade)
    
    # Output
    Grade: B
    

    A common pitfall is misaligned indentation:

    # Incorrect (inconsistent indentation — will raise IndentationError)
    # if score >= 90:
    #   grade = "A"      # 2 spaces
    #     bonus = True    # 4 spaces
    

    2.2 Spacing Around Operators and After Commas

    PEP 8 recommends adding spaces to improve readability:

    # Good
    total = 5 + 3
    numbers = [1, 2, 3, 4]
    message = "Hello, " + "World!"
    
    # Not recommended (harder to read)
    # total=5+3
    # numbers=[1,2,3,4]
    
    # Output
    # 8
    # [1, 2, 3, 4]
    # Hello, World!
    

    3. PEP 8 Naming Conventions

    PEP 8 defines common patterns for naming so that code looks consistent across projects.

    3.1 Variables and Functions: snake_case

    def calculate_total_price(unit_price, quantity):
        total_price = unit_price * quantity
        return total_price
    
    price = calculate_total_price(9.99, 3)
    print(price)
    
    # Output
    29.97
    

    3.2 Classes: PascalCase

    class BankAccount:
        def __init__(self, owner, balance=0):
            self.owner = owner
            self.balance = balance
    
        def deposit(self, amount):
            self.balance += amount
    
    
    account = BankAccount("Alice", 100)
    account.deposit(50)
    print(account.balance)
    
    # Output
    150
    

    3.3 Constants: UPPER_CASE_WITH_UNDERSCORES

    MAX_CONNECTIONS = 100
    DEFAULT_TIMEOUT_SECONDS = 30
    
    print(MAX_CONNECTIONS, DEFAULT_TIMEOUT_SECONDS)
    
    # Output
    100 30
    

    4. Formatting Lines, Imports, and Expressions

    4.1 Line Length and Line Breaks

    PEP 8 recommends:

    # Breaking a long function call over multiple lines
    result = some_long_function_name(
        first_argument,
        second_argument,
        third_argument,
    )
    
    print(result)
    
    # Output
    # (Whatever some_long_function_name returns; structure shows style, not behavior.)
    

    4.2 Import Style

    PEP 8 import guidelines:

    # Good
    import math
    import os
    
    from datetime import datetime
    
    # Not recommended
    # import math, os
    # from datetime import *
    
    print(math.pi, os.name, datetime.now().year)
    
    # Output
    # 3.141592653589793 <your_os_name> <current_year>
    

    4.3 Formatting Complex Expressions

    Use spaces and parentheses to clarify intent:

    # Without parentheses, but with clear spaces
    score = 10 * 2 + 5
    
    # With parentheses to emphasize grouping
    adjusted_score = (10 * 2) + 5
    
    print(score, adjusted_score)
    
    # Output
    25 25
    

    5. Using Linters and Formatters: flake8 and black

    Following all style rules manually is hard. Linters and formatters automate this.

    5.1 flake8: Style and Error Checker

    flake8 analyzes your code and reports style violations and some logical issues.

    Install:

    pip install flake8
    

    Run in your project folder:

    flake8 .
    

    You’ll see messages like:

    lesson.py:10:5: E303 too many blank lines (3)
    lesson.py:15:12: E225 missing whitespace around operator
    

    You then fix those lines in your editor.

    5.2 black: Automatic Code Formatter

    black automatically reformats your code to comply with a consistent style.

    Install:

    pip install black
    

    Format a file or folder:

    black lesson.py
    black .
    

    black will:

    # Before black (harder to read)
    value=[1,2,3]
    if value: print("Not empty")
    
    # After black (formatted)
    value = [1, 2, 3]
    if value:
        print("Not empty")
    
    # Output
    Not empty
    

    You can configure your IDE (e.g., VS Code, PyCharm) to run black on save and flake8 on file analysis, so style issues are automatically fixed or highlighted.


    Summary / Key Takeaways

    In this lesson on Python Syntax Rules and Style (PEP 8), you have learned:

    Python Programming – Complete Course with Practical Examples — Python Syntax, Indentation, and Core Concepts

    Getting Started with Python and the Course

    Python Syntax, Indentation, and Core Concepts

    Variables, Data Types, and Type Conversion

    Operators, Expressions, and Control Flow

    Loops and Iteration Patterns

    Working with Strings in Depth

    Collections: Lists, Tuples, Sets, and Dictionaries

    Functions and Program Structuring

    Functional Programming Concepts in Python

    Modules, Packages, and Code Organization

    Error Handling and Debugging Fundamentals

    File Handling and Data Formats

    Object-Oriented Programming in Python

    Advanced Python: Iterators, Generators, and Decorators

    Python Standard Library for Real-World Tasks

    Python for Automation and Scripting

    Testing and Quality Assurance in Python

    Tutorial Not Found