print('Hello'Cell In[1], line 1 print('Hello' ^ SyntaxError: incomplete input
Notebook explaining basic errors and how to debug
Python errors usually come with a message that describes what went wrong. Below are some fo the most common.
A SyntaxError happens when Python doesn’t understand the code structure (missing a parenthesis, colon, etc.).
A NameError occurs when you try to use something that hasn’t been defined yet.
TypeError means the wrong type of object was used.
ValueError means the type was right but the value didn’t make sense.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[4], line 1 ----> 1 "3" + 3 TypeError: can only concatenate str (not "int") to str
IndexError means you asked for a position that doesn’t exist.
NOTE: Python allows reverse indexing, so negative index values count back from the end!
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[7], line 1 ----> 1 numbers[5] IndexError: list index out of range
FileNotFoundError and PermissionError happen when files or paths don’t exist or can’t be accessed. Relative vs. absolute paths, and read/write permissions, can all matter here.
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Cell In[10], line 1 ----> 1 open('missing_file.txt') File /opt/anaconda3/lib/python3.12/site-packages/IPython/core/interactiveshell.py:324, in _modified_open(file, *args, **kwargs) 317 if file in {0, 1, 2}: 318 raise ValueError( 319 f"IPython won't let you open fd={file} by default " 320 "as it is likely to crash IPython. If you know what you are doing, " 321 "you can use builtins' open." 322 ) --> 324 return io_open(file, *args, **kwargs) FileNotFoundError: [Errno 2] No such file or directory: 'missing_file.txt'
Resolve issues through debugging and think like like a scientist about to figure out the cause of, and solution, to problems.
Instead of guessing what a printed value means, f-strings let you add context directly in the output. They are one of the easiest ways to add clarity to print statements and much more.
Comment and Change Slowly
Use # to comment out lines temporarily. Make one change at a time and re-run to see the effect.