Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 149 ยท Getting Started

Syntax and Indentation

Learn how Python reads your code - statements, indentation blocks, long lines, case sensitivity and comments - and how to fix IndentationError and SyntaxError.

Every language has grammar rules. In English, you end a sentence with a period. In Python, the rules are few and strict, and one of them surprises almost everyone coming from other languages: indentation is part of the syntax. The spaces at the start of a line decide which code belongs together.

This lesson covers the rules you need before writing anything bigger than a one-liner: how statements are separated, how indented blocks work, how to split long lines, why Name and name are different, and how to write comments. You'll also learn to read the two errors these rules produce most often, SyntaxError and IndentationError.

Statements and lines

A Python program is a sequence of statements, and the simple rule is: one statement per line. The end of the line ends the statement. There are no semicolons to remember.

Python One statement per line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python runs these from top to bottom. The first three lines are assignment statements; the last one is an expression statement that calls a function.

You can put several statements on one line by separating them with semicolons, as in x = 1; y = 2. It works, but the style guide for Python, called PEP 8, asks you not to. One statement per line is easier to read and debug.

Indentation creates blocks

Some statements control other code: if runs code only when a condition is true, for repeats code, def defines a function. These are called compound statements. Each one has a header line ending in a colon :, followed by an indented block of code that belongs to it:

Python Blocks are defined by indentation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read it the way Python does:

  • The colon after if temperature > 25 says "a block follows".
  • Both indented print() lines form the block. They run only if the condition is true.
  • The first line that goes back to the left margin ends the block. print("This line always runs.") is outside the if.

Change temperature to 18 and run it again: the two indented lines are skipped, but the others still run.

Many languages use braces { } to mark blocks and treat indentation as decoration. Python uses the indentation itself. That's why Python code from different people tends to look the same: the layout and the meaning can't disagree.

The indentation rules

  • Use 4 spaces per level. That's the universal convention, and every Python editor can do it for you when you press Tab.
  • Every line in a block must have exactly the same indentation.
  • Blocks can be nested. Each nested block is indented one more level.
  • Don't mix tabs and spaces. Python 3 refuses code where the mix makes the indentation ambiguous.

Here is a nested block, an if inside a for:

Python Nested blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A block can't be empty. If you need a placeholder while you sketch your program, write pass, a statement that does nothing:

Python
if temperature > 40:
    pass  # TODO: decide what to do in a heat wave

When indentation goes wrong

Python checks your whole file's syntax before running any of it. If the indentation doesn't make sense, nothing runs and you get an error that points at the problem line:

Python An IndentationError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that even the first print() never ran: the error happened while Python was reading the file. The message names the file, the line number and the kind of problem. Remove the extra space and the program works.

The common indentation errors are:

  • unexpected indent: a line is indented when nothing called for a block.
  • expected an indented block: a header line ends with : but the next line isn't indented.
  • unindent does not match any outer indentation level: a line moved back left, but not to a level used before.

Tip: When you get a SyntaxError, look at the line it names and also the line just before it. A missing closing parenthesis or a missing colon on one line is often only noticed on the next.

Long lines

PEP 8 suggests keeping lines under about 79 characters so code fits side by side in an editor. When a statement gets long, you can continue it on the next line. The best way is implicit continuation: inside parentheses (), square brackets [] or braces {}, Python ignores line breaks until the brackets close.

Python Splitting long lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Inside brackets, the indentation of continuation lines doesn't matter to Python, so you're free to line things up in a readable way. A trailing comma after the last item, as in "blue", above, is allowed and makes adding items later tidier.

There is also explicit continuation: a backslash \ at the very end of a line joins it with the next one.

Python
total = 1250 + 180 + \
        65 + 40

It works, but it's fragile: a single invisible space after the backslash breaks it. Prefer parentheses.

Python is case-sensitive

Uppercase and lowercase letters are different characters to Python. score, Score and SCORE are three unrelated names, and the built-in function is print, not Print:

Python Case matters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line raises a NameError, Python's way of saying "I don't know anything called Print". Unlike the IndentationError earlier, this one happens while the program is running, so the first two lines print before it fails.

Keywords are case-sensitive too. True, False and None start with a capital letter; if, for, while and def are all lowercase. Writing true or If gives you an error.

Comments

A comment starts with # and runs to the end of the line. Python ignores it completely. Comments are notes for people reading the code, including future you.

Python
# Convert the price from cents to dollars.
price = cents / 100

discount = 0.15  # 15% for members

Good comments explain why, not what. x = x + 1 # add one to x repeats the code; retries = retries + 1 # the server sometimes drops the first request tells the reader something they couldn't see.

Python has no special syntax for block comments: put a # at the start of each line. Most editors do this for you with Ctrl + / (or Cmd + /).

You'll also see triple-quoted strings ("""like this""") placed right under a function or at the top of a file. Those are docstrings, real strings that document the code and that tools can read. You'll write them in Functions.

Whitespace inside lines

Indentation at the start of a line is meaningful. Spaces inside a line mostly aren't: total=price*quantity and total = price * quantity mean the same thing. PEP 8 recommends one space around = and most operators, a space after commas, and no space just inside brackets:

Python
# Hard to read
items=[ 1,2,3 ]
result=items[0]*2+1

# PEP 8 style
items = [1, 2, 3]
result = items[0] * 2 + 1

Blank lines are ignored too. Use them to separate the logical steps of your program, the way paragraphs separate ideas in writing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What ends a block of code that belongs to an if statement?

    Python marks blocks with indentation only. When a line returns to the outer indentation level, the block is over.
  2. 2. Which character must end the header line of an if, for or def statement?

    The colon announces that an indented block follows on the next lines.
  3. 3. A file has an IndentationError on line 5. What happens to lines 1 to 4 when you run it?

    Python reads and checks the whole file before running it. Syntax and indentation errors stop the program before the first line executes.
  4. 4. What is the recommended way to split a long expression over several lines?

    Line breaks inside (), [] or {} are ignored, so parentheses are the safest choice. A backslash works but breaks if anything follows it on the line.
  5. 5. You defined total = 5 and then run print(Total). What happens?

    total and Total are different names. Python has never seen Total, so it raises NameError.

Summary

  • Write one statement per line. Semicolons are allowed but discouraged.
  • Header lines (if, for, def, ...) end with a colon, followed by an indented block.
  • Indent with 4 spaces, keep every line in a block at the same level, and never mix tabs and spaces.
  • Use pass as a placeholder for an empty block.
  • SyntaxError and IndentationError stop the program before it starts; check the named line and the one before it.
  • Split long lines inside parentheses or brackets; avoid backslash continuation.
  • Python is case-sensitive: name, Name and NAME are different.
  • Comments start with #. Explain why, not what.

Next: Variables and Names, where you'll learn how Python stores values and how to name them well.