Python — Syntax
Indentation defines structure
Most languages use curly braces {} to group code into blocks. Python uses indentation — whitespace at the start of a line:
if age >= 18:
print("Adult") # indented block
print("You can vote")
else:
print("Minor") # indented block
The standard is 4 spaces per indent level. Using tabs or mixing spaces and tabs causes TabError. Your editor should be configured to insert 4 spaces when you press Tab.
No semicolons
Python doesn't use semicolons to end statements. Each line is its own statement:
name = "Ada"
age = 25
print(name)
You can put multiple statements on one line with semicolons, but don't:
# Legal but ugly
name = "Ada"; age = 25; print(name)
One statement per line is the Python way.
Line continuation
Python statements end at the line break. For long expressions, wrap in parentheses:
total = (price1 + price2 + price3
+ tax + shipping)
Or use a backslash (less preferred):
total = price1 + price2 + price3 \
+ tax + shipping
Parentheses are cleaner — they work for expressions, function calls, and list comprehensions.
Comments
# This is a comment — the interpreter ignores it
x = 5 # inline comment also works
Python has no multi-line comment syntax. For multi-line explanations, use string literals:
"""
This module provides utility functions
for data processing and validation.
"""
# Regular code continues here
def process(data):
pass
Triple-quoted strings at the top of a file serve as module documentation (docstrings). They're not technically comments, but they function as documentation.
Naming conventions
Python follows PEP 8 — the community style guide:
| Element | Convention | Example |
|---|---|---|
| Variables | snake_case | student_count |
| Functions | snake_case | get_average |
| Classes | PascalCase | StudentRecord |
| Constants | UPPER_SNAKE_CASE | MAX_USERS |
| Modules | snake_case | my_module.py |
# Good
def calculate_average(scores):
total = sum(scores)
return total / len(scores)
# Bad
def CalculateAverage(Scores):
Total = sum(Scores)
return Total / len(Scores)
Python doesn't enforce conventions, but the community strongly follows PEP 8. Most editors have PEP 8 checking built in.
Dynamic typing
Python infers types at runtime — no type declarations needed:
x = 5 # int
x = "hello" # now a str — no error
x = [1, 2, 3] # now a list
Variables can hold any type at any time. This flexibility is powerful but can hide bugs. For larger projects, use type hints:
def greet(name: str) -> str:
return f"Hello, {name}!"
Type hints don't enforce types at runtime — they help editors and tools like mypy catch bugs before they happen.
Imports
# Import the whole module
import math
print(math.sqrt(16)) # 4.0
# Import specific items
from math import sqrt, pi
print(sqrt(16)) # 4.0
print(pi) # 3.141592653589793
# Import with an alias
import numpy as np
arr = np.array([1, 2, 3])
# Import everything (avoid this)
from math import *
Import at the top of the file. Standard library imports come first, then third-party, then local — separated by blank lines.
The Zen of Python
Type import this in a Python interpreter and you'll see the language's philosophy:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Readability counts.
These principles guide Python's design. Code that follows them is considered "Pythonic."
Whitespace and readability
Python ignores extra spaces in expressions:
x = 5
y = 10 + 20
But the community enforces clean formatting:
x = 5
y = 10 + 20
Use black or ruff format to auto-format your code. No debates about formatting — the tool decides.
Executable vs interactive
Python runs in two modes:
# Interactive mode — type a line, see the result
>>> print("hello")
hello
# Script mode — save a .py file and run it
$ python my_script.py
Interactive mode is great for experiments. Script mode is for real programs.
Errors are helpful
Python's error messages tell you what went wrong and where:
def greet(name)
print(f"Hello, {name}")
Output:
File "main.py", line 1
def greet(name)
^
SyntaxError: expected ':'
The ^ points to the exact location. Python errors include file name, line number, and a description. Read them carefully — they usually tell you exactly how to fix the issue.
Mini Practice
- Write a program that uses proper indentation with an if-else statement
- Add a multi-line comment at the top of a file describing what it does
- Import
randomand print a random number between 1 and 100 - Write a function with a type hint that takes a string and returns its length
- Run
import thisin a Python shell and pick your favorite Zen principle
Next: commenting your code →
Related Topics
Frequently Asked Questions about Syntax
What is Syntax in Python?
Syntax is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Syntax?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Syntax.
Why is Syntax important in Python?
Syntax is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.