7

I am quite new to LaTeX and do not know how to present a simple Python code like this in LaTeX in a professional way. Having your solutions and examples will help me a lot to learn and progress.

if transactions: Transaction.create_transactions() # if transactions = "true"
node.generate_emptyState() # empty state for all nodes
S.initial_events() # initiate initial events to start with

while not queue.isEmpty() and clock <= targetTime:
    next_e = queue.get_next_event()
    clock = next_e.time # move clock to the time of the event
    Event.execute_event(next_e)
    Queue.remove_event(next_e)

print results

3 Answers 3

13

Here is the way I like to do. Of course you can change colors, font sizes, borders and so on.

You need Pygments to use minted.

enter image description here

MWE

\documentclass[11pt,a4paper]{report}
\usepackage{tcolorbox}
\tcbuselibrary{minted,breakable,xparse,skins}

\definecolor{bg}{gray}{0.95}
\DeclareTCBListing{mintedbox}{O{}m!O{}}{%
  breakable=true,
  listing engine=minted,
  listing only,
  minted language=#2,
  minted style=default,
  minted options={%
    linenos,
    gobble=0,
    breaklines=true,
    breakafter=,,
    fontsize=\small,
    numbersep=8pt,
    #1},
  boxsep=0pt,
  left skip=0pt,
  right skip=0pt,
  left=25pt,
  right=0pt,
  top=3pt,
  bottom=3pt,
  arc=5pt,
  leftrule=0pt,
  rightrule=0pt,
  bottomrule=2pt,
  toprule=2pt,
  colback=bg,
  colframe=orange!70,
  enhanced,
  overlay={%
    \begin{tcbclipinterior}
    \fill[orange!20!white] (frame.south west) rectangle ([xshift=20pt]frame.north west);
    \end{tcbclipinterior}},
  #3}
\begin{document}
\begin{mintedbox}{python}
if transactions: Transaction.create_transactions() # if transactions = "true"
node.generate_emptyState() # empty state for all nodes
S.initial_events() # initiate initial events to start with

while not queue.isEmpty() and clock <= targetTime:
      next_e = queue.get_next_event()
      clock = next_e.time # move clock to the time of the event
      Event.execute_event(next_e)
      Queue.remove_event(next_e)

print results
\end{mintedbox}

\end{document}
3
  • Thanks. I use same packages before starting document and then same code, but it does not look like what you got. do i have to add any other code or install any library? using Overleaf by the way
    – MWH
    Feb 20, 2019 at 15:28
  • @MWH, I don't use Overleaf, so I am not sure if they have all packages needed for that. Try to read the log file to see what it says.
    – Sigur
    Feb 20, 2019 at 15:47
  • How could the margins be reduced?
    – Invenietis
    Jan 2, 2022 at 12:48
5

I prefer minted, but you can also use pythonhighlight, which is a nice frontend for the listings-package:

\documentclass{article}
\usepackage{pythonhighlight}

\begin{document}
\begin{python}
if transactions: Transaction.create_transactions() # if transactions = "true"
node.generate_emptyState() # empty state for all nodes
S.initial_events() # initiate initial events to start with

while not queue.isEmpty() and clock <= targetTime:
      next_e = queue.get_next_event()
      clock = next_e.time # move clock to the time of the event
      Event.execute_event(next_e)
      Queue.remove_event(next_e)

print results
\end{python}
\end{document}

enter image description here

Another way to achieve nice results with listings without fiddling around too much is the solarzied-package:

\documentclass{article}
\usepackage{solarized-light}

\begin{document}
\begin{lstlisting}[language=python]
if transactions: Transaction.create_transactions() # if transactions = "true"
node.generate_emptyState() # empty state for all nodes
S.initial_events() # initiate initial events to start with

while not queue.isEmpty() and clock <= targetTime:
      next_e = queue.get_next_event()
      clock = next_e.time # move clock to the time of the event
      Event.execute_event(next_e)
      Queue.remove_event(next_e)

print results
\end{lstlisting}
\end{document}

enter image description here

4
  • thanks. it also shows error. do you think it is not supported in overleaf?
    – MWH
    Feb 20, 2019 at 16:36
  • What shows which errors?
    – DG'
    Feb 20, 2019 at 16:36
  • @MWH I think overleaf uses TL 2016 and pythonhighlight appears to be from 2017, so you have to install it by hand. Just put the file pythonhighlight.sty in your overleaf project directory. Same applies to the three .sty files in the solarized package: github.com/jez/latex-solarized
    – DG'
    Feb 20, 2019 at 16:51
  • Is there a way I can add a label to the code so that I can use that piece of code as a reference? Dec 24, 2021 at 6:22
1

You can use {Piton} of the extension piton. It uses the Lua libraray LPEG of LuaLaTeX (and require LuaLaTeX). No exterior program is required.

\documentclass{article}
\usepackage{xcolor}
\usepackage{piton}

\begin{document}

\begin{Piton}
from math import pi

def arctan(x,n=10):
   """Compute the mathematical value of arctan(x)

   n is the number of terms in the sum
   """
    if x < 0:
        return -arctan(-x) # recursive call
    elif x > 1: 
        return pi/2 - arctan(1/x) 
        #> (we have used that $\arctan(x)+\arctan(1/x)=\frac{\pi}{2}$ for $x>0$)
    else: 
        s = 0
        for k in range(n):
            s += (-1)**k/(2*k+1)*x**(2*k+1)
        return s 
\end{Piton}

\end{document}

Output of the above code

It's possible to use it in conjunction with tcolorbox.

\documentclass{article}
\usepackage{xcolor}
\usepackage{piton}
\usepackage{tcolorbox}

\NewPitonEnvironment{Python}{}
  {\begin{tcolorbox}}
  {\end{tcolorbox}}

\begin{document}

\begin{Python}
from math import pi

def arctan(x,n=10):
   """Compute the mathematical value of arctan(x)

   n is the number of terms in the sum
   """
    if x < 0:
        return -arctan(-x) # recursive call
    elif x > 1: 
        return pi/2 - arctan(1/x) 
        #> (we have used that $\arctan(x)+\arctan(1/x)=\frac{\pi}{2}$ for $x>0$)
    else: 
        s = 0
        for k in range(n):
            s += (-1)**k/(2*k+1)*x**(2*k+1)
        return s 
\end{Python}

\end{document}

Output of the second code

You must log in to answer this question.

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