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:
- Core syntax rules for variables, keywords, and basic statements
- Proper indentation and spacing for readable code
- PEP 8 naming conventions for variables, functions, classes, and constants
- Line length, imports, and expression formatting
- How to use tools like flake8 and black to automatically enforce style
1. Python Syntax Rules: Variables, Keywords, Basic Statements
1.1 Variables and Identifiers
In Python, variable names (identifiers):
- Must start with a letter or underscore (
a_z,A_Z,_) - Can contain letters, digits, and underscores
- Are case-sensitive (
age,Age, andAGEare different) - Must not be a Python keyword (like
for,if,class)
# 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:
- Assignment:
name = "Alice" - Conditional:
if condition:then indented block - Loop:
for item in iterable:then indented block
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:
- Use 4 spaces per indentation level
- Do not use tabs mixed with spaces
# 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:
- Around assignment and comparison operators:
x = 1,x == 1,x >= 2
- After commas in lists, tuples, and function arguments
# 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
- Use lowercase with underscores for:
- variables:
user_name,max_items - functions:
get_user(),calculate_total()
- variables:
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
- Use CapWords / PascalCase for classes:
UserAccount,PaymentProcessor
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
- Use ALL CAPS with underscores for values treated as constants:
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:
- Maximum line length of 79 characters for code
- Use parentheses to break long expressions across multiple lines
# 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:
- One import per line
- Standard library imports, then third-party, then local imports
- Avoid wildcard imports (
from module import *)
# 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:
- Reflow long lines
- Fix spacing
- Normalize quotes and indentation
# 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 identifiers must follow strict rules: start with a letter or underscore, be case-sensitive, and must not use reserved keywords.
- Indentation defines code blocks in Python, and PEP 8 recommends using 4 spaces per level with consistent spacing around operators and after commas.
- PEP 8 naming conventions standardize identifiers:
snake_casefor variables and functions,PascalCasefor classes, andUPPER_CASE_WITH_UNDERSCORESfor constants. - Line formatting improves readability, including keeping lines under about 79 characters and using parentheses and line breaks for long expressions and function calls.
- Imports should be cleanly organized, separated into standard library, third-party, and local modules, with one import per line and no wildcard imports.
- Consistent expression formatting with clear spacing and grouping makes logic easier to understand and reduces bugs.
- Linters like flake8 help detect style and some logic issues, guiding you to fix problems before running code.
- Automatic formatters like black enforce a uniform style, saving time and ensuring your Python codebase remains clean and professional.
