-1

I just started to learn Python, and I was told that Python code gets executed line by line from the top. So that means if I have an error on line 2, the print method on line 1 should get executed, right? But sometimes it gets executed and sometimes it doesn't. I am really confused. Can somebody please help?

Example 1:

print("Python")
pint("Programming")

Output: Line 1 gets executed but line 2 doesn't because I have written pint instead of print. (As expected.)

In this case, the Python code is executed line by line.

Example 2:

print("Python")
print"Programming")

Output: Error on line 2 without executing line 1. (Unexpected)

Why Python code is not executed line by line in the above example?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Viren
  • 9
  • 2
  • 2
    There's a difference between parsing and executing code – Guy Incognito Nov 18 '20 at 08:47
  • Example 1 is syntactically correct. The code can be understood, but when it's executed, a problem is revealed. Example 2 is syntactically incorrect. The code cannot be understood, so it is not executed. – khelwood Nov 18 '20 at 08:48
  • 2
    When you run a Python script, before the script actually starts executing, the parser parses your source code. If the parser sees something which isn't valid Python syntax (when you've got a missing parenthesis, for example), your program won't even have a chance to execute, since what you've tried to run is not valid Python. If there are no syntax errors, your program runs, but will raise an exception if it encounters any runtime errors. This why they're called runtime errors, because they happen while the program is running. – Paul M. Nov 18 '20 at 08:53

1 Answers1

-2

In python the code is executed line by line, but the whole execution start only after checking for syntax errors.

The code only start to execute if all syntax errors are removed.

Shadowcoder
  • 962
  • 1
  • 6
  • 18