[Tex/LaTex] Change size of Python code in LaTeX document

codeformattingpythontypewriter

I am trying to input my Python code in a document using this template which uses the listings package. However I want to change the size of the code font i.e. any mentions of \texttt{} and the lstlisting environment.

\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage{fourier}

\usepackage[scaled]{beramono}
\usepackage{listings}
\lstset{
  language=Python, showstringspaces=false, formfeed=\newpage, tabsize=4,
  commentstyle=\itshape, basicstyle=\ttfamily, morekeywords={models, lambda, forms}
  fontsize=\footnotesize
}
\newcommand{\code}[2]{
  \hrulefill
  \subsection*{#1}
  \lstinputlisting{#2}
  \vspace{2em}
}

\begin{document}

This is the code from my file \texttt{mycode.py}:

\begin{lstlisting}
def factorial(n):
   """The factorial of a number the slow way"""

   # comments are printed in italic
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
\end{lstlisting}


\end{document}

I tried putting fontsize=\footnotesize in different places in the preamble, but this didn't work. Any suggestions?

Best Answer

Add \footnotesize to basicstyle:

\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage{fourier}

\usepackage[scaled]{beramono}
\usepackage{listings}
\lstset{
  language=Python,
  showstringspaces=false,
  formfeed=\newpage,
  tabsize=4,
  commentstyle=\itshape,
  basicstyle=\ttfamily\footnotesize,
  morekeywords={models, lambda, forms},
}
\newcommand{\code}[2]{%
  \hrulefill
  \subsection*{#1}%
  \lstinputlisting{#2}%
  \vspace{2em}%
}

\begin{document}

This is the code from my file \texttt{mycode.py}:

\begin{lstlisting}
def factorial(n):
    """The factorial of a number the slow way"""

    # comments are printed in italic
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
\end{lstlisting}


\end{document}

enter image description here

However, you should also scale down Bera Mono a bit more; in this case, \footnotesize doesn't seem necessary.

\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage{fourier}

\usepackage[scaled=0.8]{beramono}
\usepackage{listings}
\lstset{
  language=Python,
  showstringspaces=false,
  formfeed=\newpage,
  tabsize=4,
  commentstyle=\itshape,
  basicstyle=\ttfamily\footnotesize,
  morekeywords={models, lambda, forms},
}
\newcommand{\code}[2]{%
  \hrulefill
  \subsection*{#1}%
  \lstinputlisting{#2}%
  \vspace{2em}%
}

\begin{document}

This is the code from my file \texttt{mycode.py}:

\begin{lstlisting}
def factorial(n):
    """The factorial of a number the slow way"""

    # comments are printed in italic
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
\end{lstlisting}


\end{document}

enter image description here