Python uses indentation and colons to show code blocks.
A code block is a set of commands that are grouped together. Some uses of code blocks are to show what code is part of a function, loop, or branch.
- A colon : starts a code block (not a semicolon ; )
- All lines in the code block are indented (use tab key)
- The code block ends when the code is un-indented.
Example 1: For Loop
for i in range(10): print("This is in the code block.") print("It is indented.") print("This is not in the code block.")
Example 2: if/else
x = 3 if x > 0: print("x is greater than zero") x = -100 else: print("x is zero or less") x = 100 print("This line is not part of a block.") print("These lines are not indented.")
Example 3: Function definition
def my_function(): print("This is code in my function.") print("My function has three commands.") print("This is still in the code block.") print("This is not part of the function.")
Errors to Avoid
1) Unexpected indent
If you indent a line of code without a colon, you get “Unexpected Indentation” error.
print("This line is ok.") print("This line causes an error.")
2) Missing colon
You get “invalid syntax” if you forget a semicolon It will point a “^” at the spot where the colon is missing.
if text == "missing colon" print("The previous line needs a colon.") # error message looks like this: if text != "" ^ SyntaxError: invalid syntax
Do you see how it points at the spot where a colon is missing?
In this example, the third line unindents to a level that doesn’t match the first line:
3) Indents don’t match
if text == "Hello": print("It says 'Hello'") print("This indentation is wrong") # error message looks like this: IndentationError: unindent does not match any outer indentation level
4) Missing indent
if text == "Hello": print("Whoops - no indent") # error message: IndentationError: expected an indented block
The second line isn’t indented. At least one line must be indented after a colon.
Tip: use the “pass” command if you need an indented line but you don’t need Python to do anything.
if problem == False: pass else: print("There was a problem.")
If you delete the “pass” command, this code would then have an “expected an indented block” error.