如何在问题的网格内包含代码?

如何在问题的网格内包含代码?

我想在考试课上问一道题,它给出了代码,但不完整,需要补充。当然我可以使用命令\fillin,但我认为如果背景中有一个网格,我可以将代码对齐到该网格上(反之亦然),那就更好了,因为缩进在 Python 代码中起着重要作用。

我怎样才能实现这个目标?

\documentclass{exam}
\usepackage{listings} % or any other package useful for python(3) code                                                                                                                                                                        
\begin{document}
\begin{questions}
  \question[1] \textbf{Completion test} Complete the following code so that the function returns the given value or False if not possible:
  \begin{lstlisting}[language=Python, keepspaces=true, escapechar=!]
      def just_an_example(n):
          try:
              return !\fillin[int]!(n)
          !\fillin[except ValueError:]!
              return False
  \end{lstlisting}

  \question[1] \textbf{Better completion test} It would be much nicer if the code were inside a grid (without \textbackslash{}fillin-command). How to achieve that?
  \fillwithgrid{8em}
  \begin{lstlisting}[language=Python, keepspaces=true, escapechar=!]
      def just_an_example(n):
          try:
              return       (n)

              return False
  \end{lstlisting}
  This should be inside the grid not outside.
\end{questions}
\end{document}

相关内容