I have found out that I can open a secondary prompt with opening brackets ({, (, [
) and I am receiving a secondary prompt after hitting ENTER until I provide closing brackets. But how does the system recognize, when to close a secondary prompt, if opened via keyword+:
(keywords like def
, class
, if
, with
, try
)?
This has nothing to do with the Python programming language. It is a feature provided by the program that you use to edit the Python code, and in order to help you with that, we need to know which program that is.
Oh, wait. Are you talking about the dots here?
>>> ('example',
... 'another string',
... )
('example', 'another string')
This is happening at the interpreter prompt (REPL), yes. And yes, Python knows that the brackets need to be balanced in order to complete the expression.
This is a special case, because the REPL is not a place that you can type out an entire script - it requires one statement at a time.
In the Python grammar, a statement goes all the way to the end of the outermost “block” created with the keywords you describe. You cannot type another statement afterward by indenting all the way back:
>>> if True:
... pass
... x=3
File "<stdin>", line 3
x=3
^
SyntaxError: invalid syntax
Instead, the REPL has a special rule - it will end a multi-line input like this when you add a blank line:
>>> if True:
... pass
...
>>>
This means that you cannot reliably copy and paste long code examples into the terminal. For indented blocks, there needs to be a blank line after the outermost block first; and inside the blocks there must not be any blank lines. These restrictions are special for the interpreter prompt and will not apply to a script.
Please also keep in mind that the interpreter will evaluate each statement as it’s pasted in, so many scripts will still not work that way. For example, you cannot paste in a script that tries to input()
some data and then work with that data, because it will take the next line of the code as the input.
I am using a command line, I have installed python3 on my Ubuntu via sudo apt install python3.11
. But I was also using Rstudio with the Reticulate library. The way Reticulate puts in ...
differs from the behavior in the command line, which baffled me.
I see. But at the same time, the block of code has to follow certain grammar rules. If I add in command line:
if True:
_
So the first line if True
: the second line is space for indent and space for blank character and then in the third line, just a line, it ends up with an error (IndentationError: expected an indented block after 'if' statement on line 1
).