How to Add Code Listings in LaTeX
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.
Not sure it worked on your document? Paste it into LetX and compile it, free and in the browser.
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.
Related LaTeX fixes
Browse all LaTeX problems & fixes, or start with the LaTeX guide.
Try the fix in LetX
Open the editor, paste your code, and compile in seconds to see the error clear. Free, in your browser.
Open LetX Free