\documentclass{article}
\usepackage{sagetex}

\begin{document}

Other stuff:

Get Sage\TeX{} to write your \texttt{tabular} environments:\\

\begin{sagesilent}
import itertools
def tabular_from_list_of_lists(rows, xlabel='$x$', ylabel='$y$'):
    width = max(len(row) for row in rows)
    fmtentry = lambda e: '${0}$'.format(e)
    s = [r'\begin{tabular}{r|' + ('r' * width) + '}']
    s.append(''.join(['  & {0}: 0'.format(xlabel)] +
                     [' & {0}'.format(k) for k in range(1, width)] +
                     [r'\\']))
    s.append(r'\hline')
    fmtrow = lambda row: (''.join(''.join([fmtentry(a), b]) for a, b in
        itertools.izip_longest(row, [' & ']*(width-1), fillvalue='')) + r'\\')
    s.append('{0}: 0 & '.format(ylabel) + fmtrow(rows[0]))
    for n, row in enumerate(rows[1:], start=1):
        s.append('{0} & '.format(n) + fmtrow(row))
    s.append(r'\end{tabular}')
    return '\n'.join(s)
    
pascal = [[binomial(n, k) for k in range(n+1)] for n in range(10)]
\end{sagesilent}
 
\sagestr{tabular_from_list_of_lists(pascal, xlabel='$k$', ylabel='$n$')}
 
Here's a doctest-like environment:

\begin{sageexample}
  sage: def f(a):
  ...       '''This function is really quite nice,
  ...       although perhaps not very useful.'''
  ...       print "f called with a = ", a
  ...       y = integrate(SR(cyclotomic_polynomial(10)) + a, x)
  ...       return y + 1
  sage: f(x)
  f called with a =  x
  1/5*x^5 - 1/4*x^4 + 1/3*x^3 + x + 4
\end{sageexample}

What gets typeset here is the Sage-computed output; the output provided in the environment above is in \verb|file4_doctest.sage|, which can be doctested like any other Sage file.

% mess up doctest, run it


\newcommand{\foo}{some stuff}


\sage{f(\foo)}






























\end{document}