3

I'm fairly new to Python and would like to know, how exactly does Python run it's code ? Now, for an interpreted language it would make sense if the following code:

print("Hello, World!")
def foo
    print('foo')

Would print the 'Hello, World!' and then stop the execution, because there is a syntax error on the next line (missing ':'). However, the line will not be printed at all:

The output:

File "test.py", line 2
def foo
^

But the next piece of code will print 'Hello, World!' and stop the execution at the 4th line.

print("Hello, World!")
hans = 3
peter = 0
joseph = hans / peter

The output:

Hello, World!
Traceback (most recent call last):
File "test.py", line 4, in <module>
jospeh = hans / peter
ZeroDivisionError: division by zero

I know about syntax and logic types of code errors but does python interpreter care about the next line of code at all ?

I am looking forward to any contributions! Thank you!

Sk83r1l4m4
  • 153
  • 11
  • 1
    Python compiles to a byte-code that then is executed line by line by the interpreter. It will check for syntax errors but not runtime errors (it can't know about them due to several reasons, one of which is Python's duck-typing system), just like your examples show – DeepSpace Mar 07 '19 at 12:49
  • 2
    Note that `SyntaxError` exceptions occur one level up; the point where the contents of a new file is parsed and compiled, while other runtime errors occur when running the code. So the `ZeroDivisionError` can be caught and handled inside of `test.py`, but a syntax error *can't*. – Martijn Pieters Mar 07 '19 at 12:50
  • 3
    And different implementations are free to not compile at all. It's just that all current Python implementations (CPython, IronPython, Jython, PyPy, MicroPython) do use compilation in one form or another. – Martijn Pieters Mar 07 '19 at 12:52
  • 2
    @DeepSpace: not line by line, statement by statement. `def function(..): ...` is a statement, one that creates a function object from the stored code object (created at compile time) and stores the result in the current namespace, for example. – Martijn Pieters Mar 07 '19 at 12:53

0 Answers0