How does python interpreter run the code line by line in the following code?
It depends on how you run the Python interpréter. If you give it a full source file, it will first parse the whole file and convert it to bytecode before execution any instruction. But if you feed it line by line, it will parse and execute the code bloc by bloc:
python script.py
: parse full filepython < script.py
: parse and execute by bloc
The latter is typically the way you use it interactively or through a GUI shell like idle
.
It's a myth that Python is a fully interpreted language. When CPython runs a script the source code is parsed (this is where it will catch syntax errors), and compiled into bytecode (sometimes these are cached in your directory as .pyc
files) before anything is executed. In this regard Python is not all that fundamentally different than Java or C# other than that it doesn't spend much time doing any optimizations, and I believe the bytecode is interpreted one instruction at a time, instead of being JITed to machine code (unless you're using something like PyPy).
Because your understanding of the interpreter is faulty. While it is possible for the behaviour you are describing to occur for a subset of errors it is not the common case for many (most?) errors.
If the interpreter can construct what it thinks is a valid program but there is an error at run time then what you are describing will happen.
Since the case you are pointing at is a syntax error that prevents a valid program being constructed the behaviour is as you see it.