PythonTeX and pgffor (foreach)

pythontex

enter image description hereI am trying to generate a list of examples using PythonTeX and pgffor but this doesn't seem to work ?! The same example is repeated 5 times instead of getting 20 different examples. What's wrong in the MWE below ? Thank you.

\documentclass[12pt]{article}
\usepackage{amsmath, pgffor}
\usepackage{pythontex}
\pagestyle{empty}
\begin{document}
\begin{pycode}
import random 

def gcd(a,b):
   if(b==0):
      return a
   else:
      return gcd(b,a%b)

c = random.randint(400,1000)
d = random.randint(50,400)
p = gcd(c,d)
\end{pycode}

\foreach \n in {1,2,...,20}{ 
The greatest common divisor of $\py{c}$ and $\py{d}$ is 

\hfill $\gcd\left( \py{c};\py{d} \right) = \py{p}$ 

}

\end{document}

edit : Thanks to @user187803, the number of iterations is now ok, but I am always getting the same example.

Best Answer

To get 20 iterations, you have to replace 1,2,,..,20 with 1,2,...,20. You already did that in your edit.

You only draw random numbers for c and d once, so you cannot expect to get 20 different results. You need to draw new values in every iteration, e.g.

\documentclass[12pt]{article}
\usepackage{amsmath, pgffor}
\usepackage{pythontex}
\pagestyle{empty}
\begin{document}
\begin{pycode}
import random 

def gcd(a,b):
   if(b==0):
      return a
   else:
      return gcd(b,a%b)

def next():
    c = random.randint(400,1000)
    d = random.randint(50,400)
    p = gcd(c,d)
    return c, d, p
\end{pycode}

\foreach \n in {1,2,...,20}{ 
\pyc{c, d, p = next()}
The greatest common divisor of $\py{c}$ and $\py{d}$ is 

\hfill $\gcd\left( \py{c};\py{d} \right) = \py{p}$ 

}

\end{document}

enter image description here

Related Question