Sub topic 6
Multi-line statements and the ... prompt
This chapter assumes you can start the shell and read the >>> prompt. It also assumes you know Python's block syntax: if, for, def, and indentation. It explains how the shell decides that a statement is unfinished, what it does with your input in the meantime, and how to avoid the usual mistakes.
Two prompts, two states
The shell is always in one of two states. At the primary prompt, >>>, it waits for a new statement. At the continuation prompt, ..., it has read part of a statement and needs more before it can run anything.
Nothing is executed while you are at .... The shell collects lines, and once the statement is complete it compiles and runs the whole thing. Because of this, a typo on line 3 of a block only shows up after you finish the block.
The two prompts are ordinary strings stored in sys.ps1 and sys.ps2. You can change them for the current session:
>>> import sys
>>> sys.ps2 = "... "
>>> sys.ps2
'... 'Compound statements and the blank line
A compound statement is one that owns an indented block: for, while, if, def, class, with, try. After you type the line ending in a colon, the shell switches to .... You supply the indentation yourself, and the shell does not add it.
>>> for i in range(3):
... print(i * i)
...
0
1
4The empty line after print(i * i) is what tells the shell the block is finished. Without it, the shell cannot know whether you intend to add another statement to the loop body.
Function definitions work the same way. The def itself produces no output. It only binds a name.
>>> def greet(name):
... return f"Hello, {name}!"
...
>>> greet("Ada")
'Hello, Ada!'Clauses that continue a statement
You do not need a blank line between the parts of a single statement. A line such as else:, elif ...:, except ...:, or finally: at the outer indentation level continues the statement already in progress.
>>> n = 7
>>> if n % 2 == 0:
... print("even")
... else:
... print("odd")
...
oddThe shell treats the blank line as the end of the whole statement, if and else together.
Nested blocks
A nested block needs only one blank line at the end, not one per level. Indent the inner lines as you would in a file.
>>> for row in range(2):
... for col in range(2):
... print(row, col)
...
0 0
0 1
1 0
1 1Use the same indentation width throughout. Mixing tabs and spaces causes the same errors here as in a file.
Statements that continue without a colon
Not every ... prompt follows a colon. The shell also continues when the expression is syntactically unfinished.
| What you typed | Why the shell waits | How it ends |
|---|---|---|
| An opening `(`, `[`, or `{` with no match | The bracket is still open | The closing bracket is typed |
| A trailing backslash `\` | The line is explicitly joined to the next | A line with no trailing backslash |
| An opening `"""` or `'''` | The string literal is still open | The closing triple quote |
| A line ending in a colon | A block must follow | A blank line |
| A decorator line such as `@staticmethod` | It must be followed by a `def` or `class` | The definition's block ends |
For the first three, no blank line is needed. The statement is complete as soon as the closing bracket or quote appears and the line ends.
>>> total = (1 +
... 2 +
... 3)
>>> total
6
>>> config = {
... "host": "localhost",
... "port": 8080,
... }
>>> config["port"]
8080A backslash joins lines, and it must be the last character on the line, with no trailing space:
>>> text = "a" \
... "b"
>>> text
'ab'A triple-quoted string keeps the newlines you type. The echo shows them as \n because the echo is a repr, as the earlier chapter on print() and the echo explained.
>>> note = """line one
... line two"""
>>> note
'line one\nline two'What gets echoed inside a block
At the top level, an expression statement is echoed, and None is skipped. The same rule applies to expression statements inside a block at the top level, such as the body of a for loop. It does not apply inside a function body.
>>> for i in range(3):
... i
...
0
1
2
>>> def f():
... 5
...
>>> f()
>>>The loop echoes each i, because the loop body runs directly in the interactive session. The call f() returns None, so nothing is echoed, and the 5 inside the function was never displayed. Use print() when you want output from inside a function, and return when you want the caller to see a value.
Common mistakes
Starting a new statement without the blank line
If you type a top-level statement directly after a block, the shell treats it as part of the unfinished block and reports a syntax error:
>>> for i in range(2):
... print(i)
... print("done")
File "<stdin>", line 3
print("done")
^^^^^
SyntaxError: invalid syntaxThe exact wording and the caret marks differ between Python versions. The cause is the same: the loop was never closed. Press Enter on an empty ... line first, then type the next statement at >>>.
Pasting code that contains blank lines
Blank lines inside a function are normal in a file, but a pasted function with a blank line in its body is a trap in the classic shell. The first blank line ends the block, and the indented lines after it arrive at >>> and fail:
>>> def report(items):
... total = sum(items)
...
... return total
File "<stdin>", line 4
return total
IndentationError: unexpected indentHere report was defined with only the total = ... line. Remove blank lines before pasting, or put the code in a file and load it, as a later chapter describes. Python 3.13 and later ship a newer shell that handles pasted blocks better, but you should not rely on it if your code may run on older versions.
Typing one mistake on line two of a block
Since nothing runs until the block is complete, a mistake on an earlier line cannot be fixed by retyping just that line. In the classic shell, history recall works one line at a time, so you have to recall and re-enter each line of the block. The Python 3.13+ shell recalls a whole block as a single history entry, which makes editing easier. The chapter on line editing covers these differences.
Abandoning a block
If you realize partway through that the block is wrong, press Ctrl-C at the ... prompt. The shell discards everything entered so far for that statement and returns to >>>. It prints KeyboardInterrupt, and no earlier state is affected.
>>> for i in range(3):
... print(i
...
KeyboardInterrupt
>>>In this example the first mistake is the unclosed print(. A blank line would not have ended the statement, because the open bracket still keeps the shell waiting. Ctrl-C is the quick way out.
Working habits
- Keep interactive blocks short. Once a block runs past 8 to 10 lines, a file is a better place for it.
- Define small functions at the prompt so you can call them repeatedly with different arguments. If you need to change the definition, retype it. The new definition replaces the old one under the same name.
- End every block deliberately with a blank line before you type the next statement. Making this a reflex avoids the first mistake above.
- Use
print()for output inside functions and loops when you want to see values. Do not depend on the echo.
Exercises
Exercise
You type for i in range(2): and print(i) and then print("done") on the next line. The shell reports a SyntaxError. What did you leave out, and what is the correct sequence of keystrokes?
Show answer
You left out the blank line that ends the loop block. After print(i), press Enter on an empty ... line so the loop runs. Then type print("done") at the >>> prompt. The shell only treats a statement as finished once the blank line arrives, so a top-level line typed at ... looks like a badly indented part of the loop.
Exercise
You type values = [1, 2, and press Enter. The shell shows .... You then press Enter again on an empty line, and it still shows .... Why, and how do you recover?
Show answer
The open bracket [ makes the statement incomplete, so a blank line does not end it. Either finish the list by typing 3] and pressing Enter, or press Ctrl-C to discard the statement and return to >>>.
Exercise
Inside a loop at the prompt, a bare expression such as i is echoed. Inside a function body, a bare expression such as 5 is not. How do you make a function show or give back a value?
Show answer
Use print(value) to display it from inside the function, or return value so the caller receives it. When you call the function at the prompt, a returned value that is not None is echoed.