Python Syntax, Indentation & StatementsGet Certified
What Is Python Syntax?
Syntax is the set of rules that decides how Python code must be written so that the interpreter can understand it. Just as a sentence in English needs the right word order and punctuation, a Python program needs the right structure. If a rule is broken, Python stops and reports a SyntaxError before it runs the faulty code.
Python’s syntax is designed to be clean and close to plain English. It uses very few symbols, and it relies on indentation (the spaces at the start of a line) to show which lines belong together.
- Statements: each instruction is written on its own line, usually without any end-of-line symbol.
- Indentation: spaces at the start of a line group statements into blocks.
- Colons: a colon
:at the end of a line introduces an indented block. - Case sensitivity:
nameandNameare different identifiers. - Keywords: words such as
if,for, anddefare reserved and have fixed meanings.
Python Statements
A statement is a single instruction that Python can carry out, such as assigning a value, printing text, or importing a module. Python reads and runs statements one at a time, from top to bottom. There are two main kinds:
- Simple statements fit on one line. Examples are
x = 5,print("Hi"), andimport math. - Compound statements contain a block of other statements. They start with a header line that ends in a colon, such as
if,for,while,def,class,try, andwith.
A statement is different from an expression. An expression produces a value, such as 7 + 3 or len("Python"). Statements often contain expressions, for example total = 7 + 3 is an assignment statement that stores the value of the expression 7 + 3.
Indentation: How Python Groups Code
Many languages use braces { } to mark a block of code. Python uses indentation instead. Lines that are indented by the same amount belong to the same block, and a block ends when the indentation returns to the earlier level. Indentation is not decoration in Python: it changes what the program does.
- Use 4 spaces per level: this is the standard recommended by the official Python style guide, PEP 8.
- Be consistent: every line in the same block must be indented by exactly the same amount.
- Do not mix tabs and spaces: Python 3 reports an error when they are mixed in a confusing way. Most editors can insert 4 spaces when you press the Tab key.
- Start with a colon: a block follows a header line that ends with
:and it must contain at least one statement. - Use
passfor an empty block: thepassstatement does nothing and fills a block that has no code yet.
Try It: Indentation Controls What Runs
The two print() calls inside the if block are indented, so they run only when the condition is true. The last print() is at the left margin, so it always runs. Click Test My Code, run the program, then change 30 to 10 and run it again.
if block and run only when the test is true. The final line is outside the block and runs every time.# Indentation defines blocks
temperature = 30
if temperature > 25:
print("It is a warm day.")
print("Drink some water.")
print("This line always runs.")# symbol starts a comment. Python ignores it, so it is only a note for human readers.temperature = 30 is a simple assignment statement. It creates the variable temperature and stores the number 30 in it.if temperature > 25: is the header of a compound statement. Python checks whether the temperature is greater than 25. The colon at the end tells Python that an indented block follows.if block. It runs only when the condition is true.if block, so the line is outside it and always runs, whatever the temperature is.Try It: Nested Blocks with input()
Blocks can sit inside other blocks. Each new level adds another 4 spaces. The Program Input box is already filled with the age 30, so you can click Run Code straight away. Then change the number, for example to 70 or 12, and run it again to follow the other paths.
input() and converts it to a whole number with int(). An outer if checks for adults, and an inner if inside it checks for senior citizens. The last line is outside every block and always runs.age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
if age >= 65:
print("You are a senior citizen.")
else:
print("You are under 65.")
else:
print("You are a minor.")
print("Thank you!")input() shows the prompt and reads the first line of the Program Input box as text. int() converts that text to a whole number, which is stored in age. If the text is not a whole number, Python stops with a ValueError.if age >= 18: tests whether the age is 18 or more. The colon opens a block at the first indentation level, which is 4 spaces.if is itself inside the outer block. It tests whether the age is 65 or more. Its colon opens a deeper block, indented by 8 spaces.if. It runs only when the age is 65 or more.else: lines up with the inner if, so it belongs to that test. Its block runs when the age is 18 or more but less than 65.else: at the left margin lines up with the outer if, so it belongs to that test. It handles every age below 18.Tip: Always check whichifanelsebelongs to by looking at how far it is indented. Anelsepairs with theifthat has the same indentation.
Writing One Statement on Several Lines
Long statements are hard to read. Python lets you split one statement across several lines in two ways:
- Implicit continuation: inside parentheses
( ), square brackets[ ], or curly braces{ }, you can start a new line anywhere sensible. Python knows the statement is not finished until the bracket closes. This is the preferred method. - Explicit continuation: a backslash
\as the very last character of a line tells Python that the statement continues on the next line. Nothing, not even a space, may follow the backslash.
Try It: A Statement Split Across Two Lines
The Program Input box is already filled with a price of 12.5 on the first line and a quantity of 4 on the second line. Click Run Code, then change the values and run it again.
price = float(input("Enter the price: "))
quantity = int(input("Enter the quantity: "))
total = (price * quantity
+ 5)
print("Total with a 5 handling fee:", total)input() reads the first line of the Program Input box as text, and float() converts it to a decimal number. The number is stored in price.int(). The number is stored in quantity.total starts here. The opening parenthesis tells Python that the expression is not finished, so the statement may continue on the next line. price * quantity is calculated first.print() displays the label and the value of total. For a price of 12.5 and a quantity of 4, the result is 55.0.Several Statements on One Line
A semicolon ; allows more than one simple statement on the same line, for example x = 5; y = 7. It works, but most Python programmers avoid it because one statement per line is easier to read and debug. You will almost never need semicolons.
Case Sensitivity, Keywords and Identifiers
Python treats uppercase and lowercase letters as different. Name, name, and NAME are three separate identifiers. An identifier is a name you choose for a variable, function, or class. It may contain letters, digits, and underscores, but it cannot start with a digit and it cannot be a keyword. Keywords are reserved words that Python uses for its own purposes, such as if, else, for, while, True, False, and None.
Try It: Keywords and Case Sensitivity
Python’s standard library can list its reserved words. Click Test My Code to see how many keywords there are, and to confirm that two names that differ only in capitalization are different variables.
keyword module, prints how many keywords Python has, and shows the first eight of them. It then creates two variables whose names differ only in capitalization and prints both to show that they hold different values.import keyword
print("Python has", len(keyword.kwlist), "keywords.")
print("Some of them:", keyword.kwlist[:8])
Name = "Asha"
name = "Ravi"
print(Name, name)import keyword loads a standard library module that knows Python’s reserved words. The list is stored in keyword.kwlist.len() returns the number of items in the list, so this line prints how many keywords the running Python version has. The exact number can change between Python versions.[:8] selects the first eight items of the list. print() displays them as a list.Name starts with a capital letter. This statement creates a variable with exactly that name and stores the text "Asha" in it.name is written in lowercase, so Python treats it as a different variable. It stores "Ravi".Asha Ravi. If Python ignored capitalization, the second assignment would have replaced the first value, so this proves that the two names are separate.Common Syntax and Indentation Errors
- IndentationError: unexpected indent: a line is indented when Python does not expect a block. Remove the extra spaces so the line starts at the correct level.
- IndentationError: expected an indented block: a line ending with a colon has no indented line after it. Indent the next statement, or use
passas a placeholder. - IndentationError: unindent does not match any outer indentation level: a line returns to an indentation that matches no earlier level. Make the spaces match an earlier line in the block.
- TabError: tabs and spaces are mixed. Configure your editor to insert 4 spaces and convert tabs.
- SyntaxError: expected ‘:’: the colon at the end of a compound statement header is missing, for example
if x > 3. - SyntaxError (unclosed bracket or quote): an opening parenthesis, bracket, or quotation mark has no matching closing one.
- NameError caused by capitalization:
Totalandtotalare different names, so using the wrong capitalization refers to a variable that does not exist.
Python’s error message names the file and the line where the problem was noticed. If the line looks correct, check the line before it, because a missing bracket or colon is often discovered one line later.
Good Style Habits
- Use 4 spaces for each indentation level and never mix tabs with spaces.
- Write one statement per line.
- Keep lines reasonably short. PEP 8 suggests about 79 characters.
- Use blank lines to separate logical parts of the program.
- Choose lowercase names with underscores for variables, for example
total_price.
Key Takeaways
- Syntax is the set of rules for writing valid Python, and breaking a rule causes a
SyntaxError. - A statement is one instruction. Simple statements fit on one line, and compound statements own an indented block that starts after a colon.
- Python uses indentation, normally 4 spaces, to group code into blocks, and the indentation changes the meaning of the program.
- A long statement can continue on the next line inside brackets, or after a backslash.
- Python is case-sensitive, and keywords cannot be used as variable names.
- Read error messages carefully. They point to the line where Python found the problem.
Frequently Asked Questions
What is syntax in Python?
Syntax is the set of rules that define how Python code must be written. It covers things like indentation, colons, brackets, quotation marks, and keywords. If the code breaks these rules, Python reports a SyntaxError and does not run the faulty code.
Why does Python use indentation?
Python uses indentation to show which statements belong to the same block, instead of using braces like many other languages. This forces code to look organized and makes programs easier to read. The indentation is part of the syntax, so changing it can change what the program does.
How many spaces should I use for indentation in Python?
The standard recommendation in PEP 8 is 4 spaces for each indentation level. Python accepts other amounts, but every line in the same block must use the same amount. Most editors and IDEs insert 4 spaces automatically when you press the Tab key.
Can I use tabs instead of spaces for indentation?
You can use tabs consistently, but spaces are the recommended choice. Mixing tabs and spaces in the same block can cause a TabError or an IndentationError in Python 3. Configure your editor to insert spaces so the problem never appears.
What is the difference between a statement and an expression?
An expression produces a value, such as 7 + 3 or len(“Python”). A statement is a complete instruction that Python carries out, such as an assignment, an if statement, or a print call. Statements often contain expressions, for example total = 7 + 3.
How do I write a long statement on multiple lines in Python?
Put the statement inside parentheses, square brackets, or curly braces, and Python lets you continue it on the next line. You can also end a line with a backslash to continue on the next line, but nothing may follow the backslash. Brackets are the preferred method.
Do I need a semicolon at the end of a Python statement?
No. A new line ends a statement in Python. A semicolon is allowed only to put several simple statements on one line, such as x = 5; y = 7, and most programmers avoid that style.
What does “IndentationError: unexpected indent” mean?
It means a line starts with more spaces than Python expects, for example an indented line that does not follow a statement ending with a colon. Remove the extra spaces so the line lines up with the statements around it, and check that you have not mixed tabs and spaces.