[Tex/LaTex] Lstlisting Python

listingspython

I'm usinglistingspackage to put a python code inside an article. I want it to be written in \ttfamily. The problem is I can't change keywordstyle to bold text.

\documentclass{article}
\usepackage{listings}

\lstset{basicstyle=\ttfamily, keywordstyle=\bfseries}

\begin{document}
\begin{lstlisting}[language=Python]
if x==0:
    print(x)
\end{lstlisting}
\end{document}

Any help please ?
Thanks !

Best Answer

You need a font that has a bold version of the typewriter family. If you look in the .log file you will find:

LaTeX Font Info:    Font shape `OT1/cmtt/bx/n' in size <10> not available
(Font)              Font shape `OT1/cmtt/m/n' tried instead on input line 9.

A recent new choice of typewriter font with a bold version is provided by the newtxttt package:

Sample output

\documentclass{article}

\usepackage{listings,newtxtt}

\lstset{basicstyle=\ttfamily, keywordstyle=\bfseries}

\begin{document}
\begin{lstlisting}[language=Python]
if x==0:
    print(x)
\end{lstlisting}
\end{document}

An alternative is the zlmtt package:

zlmtt sample

which fits better with the standard computer modern fonts of LaTeX.

If you do not wish to change fonts in this way and just want to use the ordinary bold font, then you should switch to \rmfamily before selecting \bfseries:

Computer modern bf sample

\documentclass{article}

\usepackage{listings}

\lstset{basicstyle=\ttfamily, keywordstyle=\rmfamily\bfseries}

\begin{document}
\begin{lstlisting}[language=Python]
if x==0:
    print(x)
\end{lstlisting}
\end{document}