0

I want to put a code in my thesis appendix.

p

print('This sentence is output to the screen')
# Output: This sentence is output to the screen

a = 5

print('The value of a is', a)
# Output: The value of a is 5

I heard of using:

\begin{lstlisting}
3
  • 1
    Please show what you already tried using the lstlistings environment. What exactly is the problem here?
    – leandriis
    Feb 20, 2020 at 20:39
  • @leandriis, thanks. I mean is there any other beside lstlisting?
    – aan
    Feb 20, 2020 at 20:40
  • 1
    An alternative might also be the minted package.
    – leandriis
    Feb 20, 2020 at 20:42

2 Answers 2

1

The fastest method to insert a code you wrote in another file is using lstinputlisting. It requires \usepackage{listings}.

% firstline = 1, lastline = 10, firstnumber = 1, nolol, 
\lstinputlisting[label = {alg:file_name}, caption = {Legend}]
{file_name.extension}

label and caption are optional. The extension is mandatory. nolol means no list of listings, it should be used when you show sections of the code while explaining something about it, but don't actually insert the whole object.

The commented option changes the firstline and the lastline of the code to insert and you may also start the numbering at the firstnumber.

To insert a list of listings (codes, algorithms, whatever) use:

\lstlistoflistings

And if you need to rename title and captions use:

\renewcommand{\lstlistingname}{Caption listings name}
\renewcommand{\lstlistlistingname}{List of Codes renamed}

If you want to format the style I would suggest the following link: How to highlight Python syntax in LaTeX Listings \lstinputlistings command .

And more advices about listings in LaTeX/Source Code Listings.

1

There are lots of packages to format source code. I use listings (flexible enough for my limited needs), others swear by pygments (a Python based source code formatter, can also write out LaTeX; PygmenTEX is a package for calling it from LaTeX).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .