I've played around a little with the sagetex package (designing tests which can be randomized) and I think you should look into its documentation. sagetex allows you incorporate Sage into your LaTeX code. Since Sage is based Python, you can run Python using sagetex. There is a \sage command that lets you jump back in to work with variables you've defined before, which I think is the issue you are concerned about. You can find some examples on CTAN. Here's a cut down sample:
\documentclass[10pt]{article}
\usepackage{sagetex}
\begin{document}
\begin{sagesilent}%use sage without producing output
n, x = var('n x')
a = ZZ.random_element(-10,10)
while a == 0:
a = ZZ.random_element(-10,10)
b = ZZ.random_element(-10,10)
c = ZZ.random_element(-10,10)
d = ZZ.random_element(2,9)
ratexp1 = (a*n)/(a*n+1)
ratexp2 = (d**(d*n-1))/((d+1)**n)
ratexp3 = 1/(a*x+b)
deriv1 = diff(ratexp3,x,1)
\end{sagesilent}
\begin{enumerate} %creates the numbering for the problems.
\item $\Sigma_{n=1}^{\infty} \sage{ratexp2}$
\vskip 2 in %leaves 2 inches of space for student work
\item Find the derivative of $\sage{ratexp3}$. The answer is $\sage{deriv1}$
\vskip 2 in %leaves 2 inches of space for student work
\item Consider the series: $ \Sigma_{n=1}^{\infty}\sage{ratexp1} $
Find a formula for $s_n$, the nth partial sum.
\end{enumerate}
\end{document}
The code is choosing random elements for a,b,c,d but throws out a if a=0. I then
defined rational expressions (to be used in the problems) and even calculated a derivative. At that point, I left Sage but I can still access the past work (even in math mode) using the \sage command; eg. \sage{ratexp2}.
Note: although I used a = ZZ.random_element(-10,10) to produce random integers, you can use the typical Python commands to produce random numbers. You'll also need to install Sage, along with the style file. Just like the python package, compiling the code produces an intermediate file (.sage file) which you process with Sage.
sagetex is a very powerful package.
\tdegfin your main document (outside\begin{python}...\end{python}) and it should print the equivalent of\tdegcin Fahrenheit? As in-3.889? By the way, your Fahrenheit calculation is incorrect:tdegf = (tdegc - 32.0)*(5/9). – Werner Oct 30 '11 at 15:51