dlp96 dlp96 - 1 month ago 3
Python Question

How does python interpreter run the code line by line in the following code?

I have read that the interpreter runs the code line by line and reports the error if any at the same time and stops the further execution.
So in python, consider the file


print "Hello world"
12variable = 'bye'
print 12variable

Now according to the working of interpreter, the interpreter would run the first line i.e. it prints hello world first and then show the syntax error in the next line (line-by-line working). Hence the expected output is:

Hello world
12variable = 'bye'
SyntaxError: invalid syntax

But the actual output is -

12variable = 'bye'
SyntaxError: invalid syntax

Why it is not printing
Hello World
at the first?


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 file
  • python < script.py : parse and execute by bloc

The latter is typically the way you use it interactively or through a GUI shell like idle.