Python Syntax - A Comprehensive Guide
Learn Python syntax from scratch: indentation rules, variables, comments, data types, loops, conditionals, and functions — with runnable examples.
Python syntax is the set of rules that defines how a Python program must be written so the interpreter can understand and execute it. Unlike languages such as C or Java, Python uses whitespace indentation instead of curly braces to delimit blocks of code, and it reads much like plain English — which is one of the main reasons Python is a popular first language for beginners.
This chapter covers the essential building blocks of Python syntax: indentation, statements, comments, variables, data types, operators, control flow, loops, functions, and a few common gotchas.
Indentation
In Python, indentation is not a style preference — it is part of the language grammar. The interpreter uses indentation to determine which statements belong to the same block. The standard convention (and the one enforced by most linters) is 4 spaces per level.
Mixing tabs and spaces in the same file causes an IndentationError. Use one or the other consistently — the Python style guide (PEP 8) recommends spaces.
Common indentation errors
# IndentationError: expected an indented block
if True:
print("oops") # missing indentation# IndentationError: unexpected indent
x = 1
y = 2 # indented for no reasonStatements and Line Continuation
Each Python statement normally occupies one line and does not end with a semicolon (though a semicolon is technically valid). When a statement is too long, you can break it across lines in two ways.
Implicit continuation inside brackets — any open (, [, or { lets you continue on the next line:
total = (
100
+ 200
+ 300
)
print(total) # 600Explicit continuation with a backslash (\):
result = 1 + 2 + 3 \
+ 4 + 5
print(result) # 15You can also place multiple statements on one line with a semicolon, but this is discouraged:
x = 1; y = 2; print(x + y) # works, but avoid this styleComments
Comments explain intent and are ignored by the interpreter. Python has two kinds.
Single-line comments
Start a comment with #. Everything after # on that line is ignored:
# Calculate the area of a circle
radius = 5
area = 3.14159 * radius ** 2 # ** is the exponentiation operator
print(area)Multi-line comments (docstrings)
Python has no dedicated block-comment syntax. The convention is to use triple-quoted strings. When placed at the start of a function, class, or module, they become docstrings — accessible at runtime via help():
def greet(name):
"""Return a greeting for the given name.
Args:
name (str): The person's name.
"""
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!Variables and Assignment
A variable is created the moment you assign a value to it. Python is dynamically typed, so you do not declare a type:
x = 10 # integer
pi = 3.14 # float
name = "Alice" # string
active = True # booleanYou can assign multiple variables on one line:
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3Or assign the same value to several variables at once:
x = y = z = 0
print(x, y, z) # 0 0 0Variable names are case-sensitive (age, Age, and AGE are three different variables). For more on naming rules and conventions, see the Python Variables chapter.
Data Types
Every value in Python has a type. The most common built-in types are:
| Type | Example | Notes |
|---|---|---|
int | 42 | Arbitrary precision integer |
float | 3.14 | 64-bit floating point |
str | "hello" | Immutable sequence of Unicode characters |
bool | True / False | Subclass of int (True == 1, False == 0) |
list | [1, 2, 3] | Ordered, mutable sequence |
tuple | (1, 2, 3) | Ordered, immutable sequence |
dict | {"a": 1} | Key-value mapping |
set | {1, 2, 3} | Unordered collection of unique values |
NoneType | None | Represents the absence of a value |
Check the type of any value with type():
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>For a deeper look at types, see the Python Data Types chapter.
Operators
Python supports several categories of operators.
Arithmetic operators
a, b = 10, 3
print(a + b) # 13 — addition
print(a - b) # 7 — subtraction
print(a * b) # 30 — multiplication
print(a / b) # 3.3333... — true division (always returns float)
print(a // b) # 3 — floor division
print(a % b) # 1 — modulo (remainder)
print(a ** b) # 1000 — exponentiationComparison operators
Comparison operators return True or False:
print(5 == 5) # True
print(5 != 3) # True
print(5 > 3) # True
print(5 < 3) # False
print(5 >= 5) # True
print(5 <= 4) # FalseLogical operators
print(True and False) # False
print(True or False) # True
print(not True) # FalseFor a complete reference with assignment, bitwise, and identity operators, see the Python Operators chapter.
Strings
Strings are sequences of Unicode characters. They can be enclosed in single quotes, double quotes, or triple quotes:
s1 = "Hello, World!"
s2 = 'Hello, World!'
s3 = """This string
spans multiple lines."""f-strings (formatted string literals)
Introduced in Python 3.6, f-strings are the recommended way to embed expressions inside strings:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# My name is Alice and I am 30 years old.Common string operations
s = "python"
print(s.upper()) # PYTHON
print(s.capitalize()) # Python
print(len(s)) # 6
print(s[0]) # p (indexing)
print(s[1:4]) # yth (slicing)
print(s + " rocks") # python rocks (concatenation)Lists
A list is an ordered, mutable collection. Items can be of mixed types:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry (negative index = from end)
fruits.append("date")
print(fruits) # ['apple', 'banana', 'cherry', 'date']
print(len(fruits)) # 4Control Flow
The if / elif / else statement
Use if, elif (else-if), and else to branch on conditions:
score = 75
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}") # Grade: BA key gotcha: unlike many languages, Python has no switch/case syntax before Python 3.10. For multiple conditions on the same variable, use elif chains or a dictionary lookup. Python 3.10+ introduced the match statement as a structural pattern-matching alternative.
For a complete reference, see the Python If Else chapter.
The for loop
The for loop iterates over any iterable — a list, string, range, or other sequence:
Use range() to iterate a specific number of times:
for i in range(5):
print(i) # 0, 1, 2, 3, 4Use enumerate() when you need both the index and the value:
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)
# 0 red
# 1 green
# 2 blueThe while loop
The while loop repeats as long as its condition is True:
Always make sure the condition will eventually become False, otherwise you get an infinite loop.
break, continue, and else on loops
break— exits the loop immediatelycontinue— skips the rest of the current iteration and moves to the nextelseon a loop — runs after the loop completes normally (i.e., without hittingbreak)
for n in range(10):
if n == 3:
continue # skip 3
if n == 6:
break # stop at 6
print(n)
# 0 1 2 4 5Functions
Functions let you package reusable logic under a name. Define a function with def:
def add(a, b):
"""Return the sum of a and b."""
return a + b
result = add(3, 4)
print(result) # 7Default parameter values
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Hi") # Hi, Bob!Returning multiple values
Python functions can return multiple values as a tuple:
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4, 1, 5, 9])
print(low, high) # 1 9For more detail, see the Python Functions chapter.
Keywords
Python reserves certain words for the language itself. You cannot use them as variable names:
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yieldIf you accidentally use a keyword as a variable name, Python raises a SyntaxError:
# SyntaxError: invalid syntax
for = 10Modules and Imports
Python code is organised into modules (.py files). You import a module's contents with import:
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793Import specific names with from ... import:
from math import sqrt, pi
print(sqrt(25)) # 5.0Use an alias to shorten long module names:
import datetime as dt
today = dt.date.today()
print(today) # e.g. 2026-06-19