\documentclass[../../book.tex]{subfiles}
\graphicspath{{\subfix{.}}}


\begin{document}

\chapter{Common Errors}
\label{Errors}
\setcounter{section}{-1}  % Start subsections from 0

Here is a fact worth coming to terms with: a significant amount of your time spent coding will be spent debugging your code. This means you will spend time looking for mistakes in your code.  In general, there will be two kinds. First, you will write code that the Python interpreter cannot use.  There might be many reasons for this, such as improper \cite{syntax}, missing \cite{white_space}, or trying to use a bit of data that simply does not exist. These will produce errors that Python will tell you about. Second, you will write code that will run, but will give you wrong results.  This might be because you forgot to account for the units you are working in or perhaps simply implemented the task incorrectly. 

The second problem is much harder to provide general diagnoses of. We simply point out that is \textit{always} a good idea to run your program using a test case or two, in order to verify the results you are getting are correct. The first case can be simpler to address, since Python will often tell you what went wrong.  Nevertheless, the first few times you encounter the messages Python gives, you might need help understanding them.  This chapter attempts to give a bit of background about what the most common types of errors are, and why they are happening. 

\section{General advice}
Though we will address several of the most common errors below, there are so many possible errors we cannot explain them all.  Thus, it is worth a brief word on how to troubleshoot errors in general. 

Historically (\textit{i.e.}, since roughly 2010) one of the best ways to solve a problem was to copy and paste the error message directly into Google, perform a search, and then read any of the Stack Overflow or Stack Exchange pages that come up.  These sites are devoted to discussion of programming concepts and trouble shooting. Sometimes they have very detailed  answers, but often they also have fairly straightforward answers. They will also often provide links to other discussions related to the error. By reading these discussions, you can learn a lot about the specific issue you are encountering and general programming concepts. 

It is also worth mentioning that, since 2023, LLM-based AI tools (like ChatGPT, Claude, Gemini, Co-Pilot, etc.) can provide answers to problems you are encountering.  Again, a good approach is to directly paste the error message into the AI tool.  However, you can also directly paste in the code that gave the error and ask the AI tool to explain what is going wrong. You can also ask the AI tool for solutions to the problem you are having. 

A few words of caution are in order here. First, while AI tools can be useful, it can also supply answers that are simply wrong. When you are new to coding, it can be hard to know if this is the case---though if try them and they simply don't run, that is clear enough. However, even if they do run, make sure to take the time to understand what is happening in the code. One way to do this is to also ask the AI tool to explain what when wrong and why, as well as how the solution it provided solved this problem. Taking the time to do so  ensures that the solution provided by the AI tool is doing what you want and also helps you learn something about programming. Of course, you can also always fall back to the use of Stack Overflow and Stack Exchange for further explanation, if you find those from the AI tool lacking. 

While this above approach will work in general, but it is worth examining a few problems that are commonly encountered. Understanding these might save you a bit of time down the road.  



\section{Syntax Errors}
\setcounter{subsection}{-1}  % Start subsections from 0

Syntax describes the `grammar' of the programming language. It controls how the interpreter understands what you are asking of it. Thus, when you fail to use proper grammar, it cannot work. 

There are a number of potential issues, but the ones that are most common to Python are:

\subsubsection{Incorrect indentation}
In Python, white space can have meaning. Specifically, the white space at the start of a line controls what belongs to a code \cite{block}. All code that is in the same block must have exactly the same amount of leading white space. Some people use spaces for this, some use tabs. In this book, we have used tabs, with a width = 4 spaces. 

If you make an indentation error, then your code will likely not run. Instead, when you try to run your code, you will get a message like: `\lstinline{expected an indented block}''.

\subsubsection{Unmatched brackets and parentheses}

Python uses things like square brackets, curly brackets, and parentheses in the declaration of collections like lists, dictionaries, sets, etc. A common mistake is to open one such bracket and then not close it.  This is very common when you nesting these collections, like in a list of lists. When you do so, you will likely get an error telling you this. 

\lstinline{``'[' was never closed''}

In the slightly less common case that you added too many closing brackets, you will get a message that things are unmatched. 

\lstinline{``unmatched ']'''}

However, we also use parentheses in calling functions.  When we call a function, we pass arguments between parentheses.  If you open these, but do not close them, you will get:

\lstinline{``incomplete input''}

if you try to close one you haven't opened, you will again get a `unmatched' error. 



\subsubsection{Missing colon}
The beginning of a new code block usually ends with a colon. For example, if statements end with a colon, as do the opening line of a for loop. If you are missing this, the Python interpretor will not run, and you will get an error message:

\lstinline{''expected ':'''}


\subsubsection{Missing comma}
If you create a collection, you will separate items in this collection with commas. If you forget the comma, the interpretor will not run and you will get an error message.

\lstinline{"invalid syntax. Perhaps you forgot a comma?"}


\section{Segmentation Fault}
In general, segmentation faults are encountered when you try to access a bit of memory that cannot be accessed, or you try to access a specific value that no longer exist. In Python, it is very rare to encounter a true segmentation fault, but there are a number of other errors that are closely related, which you might encounter:

\begin{itemize}
    \item [TypeError]: This occurs when you are attempting to perform an action that cannot be performed on the data type. For instance, if you try to convert a \cite{list} to a \thelstlisting{string}, you will get such an error. 

    \item [IndexError]: This occurs when you attempt to access a value at an \cite{index} that does not exist.  For instance, imagine you had the list \lstinline{mylist = [1, "purple", True]}.  If you tried to access the index 3, you would get such an error.  \lstinline{mylist[3]} will yield: \lstinline{'list index out of range'}.  In our experience, this is most commonly encountered when you are using a counter to advance elements in a list, and then advance it too far. For instance, you could be using \lstinline{enumerate} with a list, but then accessing elements 1 value ahead (so-called 'look ahead'). If you don't take care, you will automatically try to access indecies that do not exist. 

    \item[KeyError]: These happen when using mapping data types, like dictionaries, but then attempt to use a key that does not exist.  In our experience, this happens most often when you are building up a dictionary and then attempt to access a value that you have not yet added. 

    \item [NameError]: This occurs when you try to use a variable that has not yet been created. There are probably three ways you will encounter this error.  First, you may have a typo---using a name that you did not intend to---in either the declaration of the variable or the useage of it. Second, you may being trying to access a variable that doesn't exist due to scope. Perhaps the variable was created in a function, but you are trying to access the variable outside the function.  Finally, you may have previsouly had a perfectly good code, and then cut and pasted parts, accidently moving the usage of a variable to before it was declared. 
\end{itemize}


% \section{Argument Mismatch}
% This is closely related to ideas like the IndexError and Type errors discussed above. This error occurs in situations where you...




\section{Overflow}
This is the name assigned to the problem of trying to generate a number that is too large for Python. As noted in the discussion of data types there is no limit for integers, but there is for floats. Thus, if you try to generate a float that is too large or too small for Python, you will get this error. These errors are why you might encounter `strange' units in computational chemistry.  For instance, units can be used that allow avoidance of Planck's constant. Since this constant is very small, calculations that might involve the inverse square larger can lead to such errors. 


\section{Using mutable objects incorrectly}

We conclude this chapter with a discussion of something that is not, strictly speaking, an error.  But it is encountered commonly enough that we feel it should be mentioned here. The basic problem is that one accidentally changes the value of a mutable object. This idea was discussed in our the chapter on data types (Chapter \ref{DataTypes}) and again at the end of the chapter on function (Chapter \ref{ch:functions}, so please read that section.  We mention it here, because it is a commonly encountered problem. 



\end{document}