247 \item \typ{return} |
247 \item \typ{return} |
248 \end{itemize} |
248 \end{itemize} |
249 \end{frame} |
249 \end{frame} |
250 |
250 |
251 \begin{frame}[fragile] |
251 \begin{frame}[fragile] |
|
252 \frametitle{Functions - Calling them} |
|
253 \begin{lstlisting} |
|
254 In [15]: f() |
|
255 --------------------------------------- |
|
256 \end{lstlisting} |
|
257 \alert{\typ{TypeError:}}\typ{f() takes exactly 1 argument} |
|
258 \typ{(0 given)} |
|
259 \begin{lstlisting} |
|
260 In []: f(0) |
|
261 Out[]: 0.0 |
|
262 In []: f(1) |
|
263 Out[]: 1.8414709848078965 |
|
264 \end{lstlisting} |
|
265 \end{frame} |
|
266 |
|
267 |
|
268 \begin{frame}[fragile] |
|
269 \frametitle{Functions - Default Arguments} |
|
270 \begin{lstlisting} |
|
271 In []: def f(x=1): |
|
272 return sin(x)+x**2 |
|
273 In []: f(10) |
|
274 Out[]: 99.455978889110625 |
|
275 In []: f(1) |
|
276 Out[]: 1.8414709848078965 |
|
277 In []: f() |
|
278 Out[]: 1.8414709848078965 |
|
279 \end{lstlisting} |
|
280 \end{frame} |
|
281 |
|
282 \begin{frame}[fragile] |
|
283 \frametitle{Functions - Keyword Arguments} |
|
284 \begin{lstlisting} |
|
285 In []: def f(x=1, y=pi): |
|
286 return sin(y)+x**2 |
|
287 In []: f() |
|
288 Out[]: 1.0000000000000002 |
|
289 In []: f(2) |
|
290 Out[]: 4.0 |
|
291 In []: f(y=2) |
|
292 Out[]: 1.9092974268256817 |
|
293 In []: f(y=pi/2,x=0) |
|
294 Out[]: 1.0 |
|
295 \end{lstlisting} |
|
296 \end{frame} |
|
297 |
|
298 \begin{frame}[fragile] |
252 \frametitle{More on functions} |
299 \frametitle{More on functions} |
253 \begin{itemize} |
300 \begin{itemize} |
254 \item Support default and keyword arguments |
|
255 \item Scope of variables in the function is local |
301 \item Scope of variables in the function is local |
256 \item Mutable items are \alert{passed by reference} |
302 \item Mutable items are \alert{passed by reference} |
257 \item First line after definition may be a documentation string |
303 \item First line after definition may be a documentation string |
258 (\alert{recommended!}) |
304 (\alert{recommended!}) |
259 \item Function definition and execution defines a name bound to the |
305 \item Function definition and execution defines a name bound to the |
260 function |
306 function |
261 \item You \emph{can} assign a variable to a function! |
307 \item You \emph{can} assign a variable to a function! |
262 \end{itemize} |
308 \end{itemize} |
263 \end{frame} |
309 \end{frame} |
264 |
310 |
|
311 \begin{frame}[fragile] |
|
312 \frametitle{Quadrature \ldots} |
|
313 \begin{lstlisting} |
|
314 In []: integrate.quad(f, 0, 1) |
|
315 \end{lstlisting} |
|
316 Returns the integral and an estimate of the absolute error in the result. |
|
317 \end{frame} |
265 |
318 |
266 \subsection{ODEs} |
319 \subsection{ODEs} |
267 |
320 |
268 \begin{frame}[fragile] |
321 \begin{frame}[fragile] |
269 \frametitle{ODE Integration} |
322 \frametitle{ODE Integration} |