Python Syntax
Syntax is the set of rules for how Python code must be written. Python’s rules are few, but one of them, indentation, is stricter than in most languages. Learn these rules once and most beginner errors disappear.
- How statements and lines work
- Why indentation defines blocks
- How to split long lines
- Python keywords and case sensitivity
Statements and lines
A Python program is a list of statements, normally one per line. Python runs them from top to bottom. No semicolon is needed at the end of a line.
city = "Pune"temperature = 31print(city, temperature)Pune 31
Indentation defines blocks
Many languages use curly braces { } to group lines. Python uses indentation: the spaces at the start of a line. A line ending in a colon : starts a block, and every line in that block must be indented by the same amount.
score = 82 if score >= 50: print("Passed") # inside the if block print("Well done") # also insideprint("Report finished") # outside: runs every timePassed Well done Report finished
Use 4 spaces per level. Every IDE inserts 4 spaces when you press Tab in a .py file. Never mix tabs and spaces in one file.
Wrong indentation is a syntax error, and Python refuses to run the file:
if True:print("not indented") File "main.py", line 2
print("not indented")
^^^^^
IndentationError: expected an indented block after 'if' statement on line 1Indenting a line that should not be indented is also an error:
print("one") print("two") File "main.py", line 2
print("two")
IndentationError: unexpected indentBlocks inside blocks
Each new block adds one more level of indentation. Python knows a block has ended when the indentation goes back.
for n in [1, 2, 3, 4]: if n % 2 == 0: print(n, "is even") else: print(n, "is odd")print("done")1 is odd 2 is even 3 is odd 4 is even done
Long lines
Python ends a statement at the end of the line, except inside brackets (), [] or {}. So the easiest way to split a long line is to wrap it in parentheses.
total = ( 120 + 80 + 45)names = ["login", "search", "checkout"]print(total, names)245 ['login', 'search', 'checkout']
A backslash \ at the end of a line also continues it, but brackets are clearer and are what the PEP 8 style guide recommends.
Several statements on one line
A semicolon lets you put two statements on one line. It works, but it hurts readability, so use it rarely.
a = 1; b = 2; print(a + b)3
Case sensitivity
Python is case-sensitive: name, Name and NAME are three different variables, and Print is not the same as print.
name = "Asha"Name = "Ravi"print(name, Name)Print("hello")Asha Ravi
Traceback (most recent call last):
File "main.py", line 4, in <module>
Print("hello")
^^^^^
NameError: name 'Print' is not defined. Did you mean: 'print'?Keywords
Keywords are reserved words with a special meaning, such as if, for and def. You cannot use them as variable names. The keyword module lists them:
import keywordprint(len(keyword.kwlist))print(keyword.kwlist)35 ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
True, False and None are keywords too, and they start with a capital letter. true or none would be treated as ordinary (undefined) names.
Check your understanding
Predict the output
x = 5if x > 3: print("big")print("end")if x > 10: print("huge")big end
Only the first if is true. print("end") is not indented, so it runs whatever the conditions are.
Quick quiz
1. What marks the start of a block in Python?
if, for, while, def and class lines end with : and the indented lines below form the block.
2. How many spaces per indentation level does PEP 8 recommend?
Four spaces is the standard. What matters most is using the same amount everywhere.
3. Which of these is a valid variable name?
class is a keyword and names cannot start with a digit.
Exercise: fix the indentation
This program should print “Even numbers:” once, then each even number, then “Done”. Fix the indentation so it runs.
Hint 1
Only the print(n) line belongs inside the if.
Hint 2
“Done” must print once, after the loop, so it should not be indented.
print("Even numbers:")for n in range(1, 7): if n % 2 == 0: print(n)print("Done")Even numbers: 2 4 6 Done
The for block holds the if, and the if block holds print(n). print("Done") sits at the left edge, so it runs once after the loop.
Program Practice
40 Python Basic Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python syntax FAQ
Does Python use semicolons?
Not normally. A newline ends a statement. A semicolon is only needed to put two statements on one line, which is rarely a good idea.
What is an IndentationError?
It is the error Python raises when lines in a block are not indented consistently, or when a block is missing after a colon.
Can I use tabs instead of spaces in Python?
Python accepts tabs, but not a mix of tabs and spaces in the same block. Use 4 spaces; every editor can insert them for you.
Is Python case-sensitive?
Yes. total and Total are different names, and built-in functions such as print must be lowercase.