Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ex1.py,

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?

like image 207
dlp96 Avatar asked Sep 04 '16 04:09

dlp96


1 Answers

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.

like image 198
Serge Ballesta Avatar answered Sep 28 '22 09:09

Serge Ballesta