When Python can't read your code
Sooner or later every program has a mistake in it. When Python can't understand a line, it stops and prints an error message instead of running the program. Learning to read these messages saves a lot of guessing.
A syntax error
Syntax is the set of rules for how code must be written, like grammar for a language. Here the text is missing its quotes:
print(Good morning)
File "main.py", line 1
print(Good morning)
^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?Read the message from the top:
File "main.py", line 1says where the problem is: line 1 of your program (on this site, your program's file is calledmain.py).- The next line shows that line of code, and the
^marks point at the part Python couldn't read. - The last line names the kind of error,
SyntaxError, with Python's guess at the cause. Its guess here (a missing comma) is wrong, which happens: the real problem is the missing quotes. The line number and the marks are usually more reliable than the guess.
With a syntax error, Python runs nothing at all, not even the lines before the mistake.
A name Python doesn't know
Here every quote is in place, but the command is misspelled:
print("Starting...")
Print("Hello")
Starting...Traceback (most recent call last):
File "main.py", line 2, in <module>
Print("Hello")
^^^^^
NameError: name 'Print' is not defined. Did you mean: 'print'?This time the first line ran and printed Starting..., and the program stopped at line 2. A NameError means Python doesn't know the name: Print with a capital P isn't print. The "Did you mean" part is often exactly right. On this site, a plain-English note under such a message explains it too.