2

I know that Python interpreter executes command line by line without compiling entire program at start. But however I do not understood why it catching syntax errors on next subsequent lines without executing starting lines.

For example, in script, if I write following statements:

print("I am first")
print("Second")
print(third")              # Syntax error. Missed one "

This gives below output:

File "script2.py", line 3

    print(third")
                ^

SyntaxError: EOL while scanning string literal

I was expecting output as below:

I am first
Second
File "script2.py", line 3

    print(third")
                ^

SyntaxError: EOL while scanning string literal

I am keen to learn why the Python interpreter exhibits this behavior.

halfer
  • 19,824
  • 17
  • 99
  • 186
Shubham S. Naik
  • 341
  • 1
  • 4
  • 14
  • It will parse what ever you give in one shot. try executing one line at a time – Shivkumar kondi Jul 28 '17 at 05:23
  • These may be of use to you: https://tomlee.co/wp-content/uploads/2012/11/108_python-language-internals.pdf and this blog post here: https://tech.blog.aknin.name/2010/04/02/pythons-innards-introduction/ – prijatelj Jul 28 '17 at 05:23
  • i'm fairly certain that no python implementation waits to catch this kind of error until the code is run- even JITs like pypy or pyjion. it's just not an efficient way to do things. the code is parsed first. – Rick Jul 28 '17 at 05:28

2 Answers2

0

Python does not interpret code directly as it is not efficient. First, it converts python code to .pyc file that is compiled bytecode and after that, it will interpret the compiled bytecode(.pyc).

If there was error in conversion of python code to '.pyc' then it will be raised at compile time; that's why you are getting an error at compile time

Best explanation can be found on the StackOverflow question

Himanshu dua
  • 2,496
  • 1
  • 20
  • 27
0

It depends on how you run the Python interpreter. 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 block by block

so go for One Line at a time

Shivkumar kondi
  • 6,458
  • 9
  • 31
  • 58