TeXbook, Chapter 20: Definitions (also called Macros) says:
Here now is the promised list of all cases when expandable tokens are not expanded. [...] Expansion is suppressed at the following times:
[...]
When TeX is absorbing the replacement text of a \def or \gdef or \read; or the text of a token variable like \everypar or \toks0; or the token list for \uppercase or \lowercase or \write. (The token list for \write will be expanded later, when it is actually output to a file.)
Inside the \foreach-loop you have directives \foo for (beneath other things) writing the tokens \aaa and \bbb unexpanded to file when the output-routine ships out the page.
But instead of \aaa and \bbb their toplevel-expansion should be written.
\documentclass[a4paper,11pt]{article} \usepackage{ProfLycee} \everymath{\displaystyle} % Really? \begin{document} \newwrite\myoutput \immediate\openout\myoutput=\jobname-corr.tex \newcommand{\foo}[2]{% \write\myoutput{% \string$\string\dfrac\unexpanded{{#1}{#2}}\string=\string\ConversionFraction\unexpanded{{#1/#2}$}% }% \write\myoutput{\string\par\string\bigskip}% } \textbf{Exercice} : simplify each fraction. \par \bigskip \foreach \n in {1,2,...,5}{% \NbAlea{3}{50}{\aaa}% \NbAlea{\aaa+1}{60}{\bbb}% $\dfrac{\aaa}{\bbb} = \dfrac{\dots}{\dots}$% % Use \ExpandArgs for optaining toplevel-expansion of \aaa and \bbb: \ExpandArgs{oo}\foo{\aaa}{\bbb}% \par\bigskip } \write\myoutput{\string\textbf{Correction} : \string\par} % Don't mix delayed/non-immediate\write with \immediate\closeout. % This might close the file before everything is written. % Better use \newpage to trigger output-routine and delayed action. \closeout\myoutput \newpage \input{\jobname-corr.tex} \end{document}
Alternatively to having TeX write when the output-routine ships out the page and playing with \newpage for triggering the carrying out of delayed actions, do everything in terms of \immediate:
\documentclass[a4paper,11pt]{article} \usepackage{ProfLycee} \everymath{\displaystyle} % Really? \begin{document} \newwrite\myoutput \immediate\openout\myoutput=\jobname-corr.tex \newcommand{\foo}[2]{% \immediate\write\myoutput{% \string$\string\dfrac\unexpanded{{#1}{#2}}\string=\string\ConversionFraction\unexpanded{{#1/#2}$}% }% \immediate\write\myoutput{\string\par\string\bigskip}% } \textbf{Exercice} : simplify each fraction. \par \bigskip \foreach \n in {1,2,...,5}{% \NbAlea{3}{50}{\aaa}% \NbAlea{\aaa+1}{60}{\bbb}% $\dfrac{\aaa}{\bbb} = \dfrac{\dots}{\dots}$% % Use \ExpandArgs for optaining toplevel-expansion of \aaa and \bbb: \ExpandArgs{oo}\foo{\aaa}{\bbb}% \par\bigskip } \immediate\write\myoutput{\string\textbf{Correction} : \string\par} \immediate\closeout\myoutput \input{\jobname-corr.tex} \end{document}
\unexpandedso just writing out the form with\aaaand\bbbeach time, you want to not do that, and write the values of those variables,