How to Add Code Listings in LaTeX
The fix
For code in LaTeX, use the listings package: load \usepackage{listings} and wrap code in \begin{lstlisting} ... \end{lstlisting}, setting the language via \lstset{language=Python}. For richer syntax highlighting, use minted, which needs Python Pygments and compiling with the --shell-escape flag.
Example
\usepackage{listings}
\lstset{language=Python, basicstyle=\ttfamily\small,
keywordstyle=\color{blue}, numbers=left}
\begin{lstlisting}
def hello():
print("Hello, LaTeX")
\end{lstlisting}Frequently asked questions
listings or minted?
listings is pure LaTeX and works everywhere with no setup. minted produces nicer highlighting via Pygments but requires Python and compiling with the --shell-escape flag.
How do I include code from a file?
Use \lstinputlisting[language=Python]{script.py} to pull an external file directly, so the listing stays in sync with the real source.
Try the fix in LetX
Open the editor, paste your code, and compile in 1 second to see the error clear — free, in your browser.
Open LetX Free