4: Functions
- Page ID
- 122322
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)- 4.1: Function Calls
- This page explains functions in programming, defining them as named sequences of statements that carry out computations. It emphasizes that functions are executed by calling their names with given arguments, like in the example "type(32)". Functions take input arguments and return results referred to as return values.
- 4.2: Built-in Functions
- This page discusses Python's built-in functions that ease common tasks, including max, min, and len. These functions return the largest or smallest values and count items or characters in strings or lists. Examples include max('Hello world') yielding 'w' and len('Hello world') resulting in 11. The page emphasizes their versatility across data types and recommends treating their names as reserved to avoid conflicts with variable names.
- 4.3: Type Conversion Functions
- This page explains Python's built-in type conversion functions: `int` converts values to integers by truncating decimals and raises errors for invalid inputs; `float` converts integers and strings to floating-point numbers; and `str` converts its argument to string format.
- 4.4: Random Numbers
- This page discusses the determinism of computer programs and the need for unpredictability in applications like games. It highlights the challenge of achieving true nondeterminism and introduces pseudorandom numbers as a solution. The page describes Python's random module, mentioning functions such as `random()` for floats, `randint()` for integers, and `choice()` for selecting random elements, as well as functionality for generating random values from various continuous distributions.
- 4.5: Math Functions
- This page discusses the Python math module, which offers a variety of mathematical functions and constants, including π. Functions are accessed using dot notation and are useful for operations like calculating logarithms and trigonometric values. It details how to convert degrees to radians and encourages validating results with known values, such as the sine of 45 degrees.
- 4.6: Adding New Functions
- This page explains how to define and use functions in Python using the "def" keyword, outlining naming conventions and structural components of function definitions. It details how to call custom functions, akin to built-in ones, and presents examples, including a simple function, print_lyrics, and another, repeat_lyrics, that invokes the former multiple times.
- 4.7: Definitions and Uses
- This page details a Python program featuring two functions, `print_lyrics` and `repeat_lyrics`, with the latter calling the former to print song lyrics twice. It emphasizes the importance of defining functions before execution and illustrates this with exercises that involve manipulating function calls and definitions to observe errors and outcomes.
- 4.8: Flow of Execution
- This page explains that the flow of execution in a program determines the order of statement execution, progressing sequentially. Function definitions do not alter this flow and are executed only upon being called. Function calls temporarily divert execution, creating layers of calls that Python manages effectively by tracking return points. Consequently, understanding a program requires following the flow of execution instead of a linear reading approach.
- 4.9: Parameters and Arguments
- This page discusses user-defined functions in Python that accept arguments, mirroring built-in functions. It features an example function, `print_twice`, which outputs its argument twice, applicable to diverse data types. The text highlights that arguments are evaluated prior to the function call and clarifies that variable names in the call do not influence the function's parameter names.
- 4.10: Fruitful functions and void functions
- This page discusses two types of functions in Python: fruitful functions, which return a value (e.g., `math.sqrt`), and void functions, which do not return a value (e.g., `print_twice`). It emphasizes the role of the `return` statement, illustrated by the `addtwo` function that sums two numbers and returns the result, showcasing how to effectively manage outputs from functions.
- 4.11: Why functions?
- This page discusses the advantages of dividing a program into functions, including enhanced readability, reduced code repetition, improved debugging, and increased reusability across programs. It also mentions that the book will illustrate these concepts through function definitions, such as a "min" function that identifies the smallest value in a list, showcasing the creation and application of functions.
- 4.12: Debugging
- This page emphasizes the importance of using spaces instead of tabs in scripts to prevent indentation issues and recommends choosing an editor that automatically manages indentation. It advises saving programs before executing them to ensure the latest version runs, and suggests using print statements for verification if there's any doubt about which version is executing, highlighting that debugging can be challenging with outdated code.
- 4.E: Functions (Exercises)
- This page includes exercises on Python programming, emphasizing the "def" keyword for function definition, creating functions, and applying logic for pay calculations and grading. It covers the role of "def" in function creation, expected outputs of function calls, and tasks like rewriting a pay function with overtime considerations and designing a grade computation function based on scores, with examples and expected responses.
- 4.G: Functions (Glossary)
- This page defines essential programming concepts such as algorithms, functions, and flow of execution. It explains algorithms as problem-solving methods, functions as sequences of statements that can accept arguments, and differentiates between fruitful and void functions. The use of dot notation for calling functions in modules and the role of import statements are discussed. Additionally, it touches on deterministic behaviors, parameters, and pseudorandom number generation.