Python is a high-level, interpreted programming language renowned for its readability and elegant syntax. Designed with the philosophy that code is read more often than it is written, Python emphasizes clarity through consistent formatting, minimal boilerplate, and expressive constructs. This article covers the core syntactic rules that govern Python programming, aligning with official standards such as PEP 8.
1. Indentation & Code Blocks
Unlike languages like C++ or Java that use curly braces {} to define scope, Python uses indentation. This is not merely aesthetic; it is syntactically required. The standard indentation is four spaces per level, as mandated by PEP 8.
def calculate_average(numbers): total = sum(numbers) count = len(numbers) if count == 0: return 0 return total / count
Mixing tabs and spaces will raise an IndentationError in Python 3. Always configure your editor to insert spaces when pressing Tab.
2. Variables & Dynamic Typing
Python is dynamically typed, meaning variables do not require explicit type declarations. The interpreter infers the type at runtime based on the assigned value. Variable names must start with a letter or underscore, contain only alphanumeric characters and underscores, and are case-sensitive.
age = 25 # int price = 19.99 # float name = "Python" # str is_active = True # bool # Multiple assignment x, y, z = 1, 2, 3
3. Comments
Comments are ignored by the interpreter and serve to explain code logic. Python supports two forms:
- Inline comments: Start with
#and extend to the end of the line. - Docstrings: Multi-line strings enclosed in triple quotes
"""or''', used primarily for documenting modules, functions, and classes.
def greet(username): """Display a personalized greeting."" # Validate input if not username: return "User not found" return f"Hello, {username}!"
4. Control Flow
Python provides standard conditional and looping constructs with clean syntax:
Conditionals
score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" else: grade = "C"
Loops
Python uses for for iteration over sequences and while for condition-based repetition. The range() function generates integer sequences.
# For loop for i in range(5): print(i) # Outputs 0 to 4 # While loop count = 0 while count < 3: count += 1
5. Functions & Docstrings
Functions are defined using the def keyword. They can accept positional, keyword, and default arguments. Return values are explicit via return.
def process_data(items, threshold=50): """Filter items above a given threshold."" return [item for item in items if item > threshold] result = process_data([10, 45, 60, 75])
6. Imports & Modules
Python organizes code into modules (.py files) and packages. Imports are handled via the import and from ... import statements.
import math from datetime import datetime import os as operating_system pi = math.pi today = datetime.now()
Best Practices & PEP 8
The Python community follows PEP 8, the official style guide. Key recommendations include:
- Use 4 spaces per indentation level
- Limit lines to 79 characters (or 99 in modern codebases)
- Use lowercase_with_underscores for functions and variables
- Use CapWords for class names
- Add blank lines between top-level definitions
- Prefer f-strings for string formatting in Python 3.6+
For official specifications, consult PEP 8 and the Python Language Reference.