-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?

3
  • 2
    There's a difference between parsing and executing code Commented Nov 18, 2020 at 8: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. Commented Nov 18, 2020 at 8: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. Commented Nov 18, 2020 at 8:53

1 Answer 1

-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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.