Reputation: 774
I have read that python is a scripting language and its execution engine consists of a interpreter that executes each code of line one by one.
I have a simple python code as-
print("1")
print("2")
print("3")
print("4)
Here line 4 print("4) contains an error(missing ending quote). When I run this program then simply get an error telling me a syntax error in line 4.
My question is that since python is interpreted and not compiled then shouldn't the output be
1
2
3
Syntax error in line 4
But it directly gives me a error message without any output for line 1, 2 and 3 just like any other compiled language like Java, C and C++
I'm new to python, Kindly explain.
Upvotes: 1
Views: 150
Reputation: 87134
It's important to realise that Python code is first compiled into an intermediate form called byte code. That byte code is then executed by the Python interpreter. It is analogous to the compilation/execution cycle of Java, if you are familiar with that, although Python can immediately execute the compiled code. The byte code is not the same as machine code that can be directly executed by the hardware, it is higher level.
In Python the compilation unit is the module which typically corresponds to a whole file, not individual statements.
So line 4 in your example will be compiled together with the previous lines, and the syntax error in line 4 prevents execution beginning.
You can get a feel for what the byte code is like by disassembling a function:
import dis
def f():
print("1")
print("2")
print("3")
dis.dis(f)
Output
2 0 LOAD_CONST 1 ('1') 3 PRINT_ITEM 4 PRINT_NEWLINE 3 5 LOAD_CONST 2 ('2') 8 PRINT_ITEM 9 PRINT_NEWLINE 4 10 LOAD_CONST 3 ('3') 13 PRINT_ITEM 14 PRINT_NEWLINE 15 LOAD_CONST 0 (None) 18 RETURN_VALUE
Upvotes: 3