Python Syntax
Python syntax is the set of rules that decides how Python code must be written. The good news is that Python syntax is small and tidy. The one rule that surprises newcomers is that indentation (the spaces at the start of a line) actually matters.
Python Indentation
Many languages use curly braces to group code. Python uses indentation instead. Lines that belong to the same block must be indented by the same amount. Four spaces is the standard.
temperature = 31
if temperature > 25:
print("It is hot today")
print("Drink some water")
print("This line always runs")It is hot today Drink some water This line always runs
The two print() lines under the if are indented, so they only run when the condition is true. The last line is not indented, so it is outside the if block and runs every time.
Indentation Errors
If you forget to indent, or mix different amounts of indentation in one block, Python stops and reports an error before running anything. Try removing the spaces in front of print in the editor to see it.
if 5 > 2:
print("Five is greater than two")IndentationError: expected an indented block after 'if' statement on line 1
Statements and Lines
Normally each statement goes on its own line, and no semicolon is needed at the end. A long expression can continue over several lines if it is inside brackets, parentheses or braces.
name = "Ayesha"
age = 24
total = (10 + 20 +
30 + 40)
print(name, age)
print(total)Ayesha 24 100
Python Is Case-Sensitive
Upper and lower case letters are different in Python. The names city, City and CITY refer to three separate variables. Keywords such as if, for and True must be written exactly as shown.
city = "Lahore"
City = "Karachi"
print(city)
print(City)Lahore Karachi
Key Python Syntax Rules
- Blocks start with a colon (:) and the lines inside them are indented
- Use 4 spaces per indentation level and do not mix tabs and spaces
- No semicolons are required at the end of statements
- Names are case-sensitive
- Strings can use single quotes or double quotes
Frequently asked questions
How many spaces should I use for indentation in Python?
The official style guide, PEP 8, recommends 4 spaces per level. Python accepts any consistent amount, but 4 spaces is what almost all Python code uses.
Can I use semicolons in Python?
Yes, a semicolon can separate two statements on one line, like x = 1; y = 2. It is allowed but discouraged because it makes code harder to read.
Does Python use curly braces?
Not for code blocks. Python uses indentation to group code. Curly braces are used for dictionaries and sets instead.