Functions
Mathematical functions as Python functions
Understanding the program flow
Local and global variables
Multiple arguments
Function argument or global variable?
Beyond mathematical functions
Multiple return values
Computing sums
Functions with no return values
Keyword arguments
Doc strings
Functions as arguments to functions
The main program
Lambda functions
Branching
If-else blocks
Inline if tests
Summary
Chapter topics
Example: Numerical integration
Exercises
Exercise 1: Implement a simple mathematical function
Exercise 2: Implement a simple mathematical function with a parameter
Exercise 3: Explain how a program works
Exercise 4: Write a Fahrenheit-Celsius conversion functions
Exercise 5: Write a test function for Exercise 4: Write a Fahrenheit-Celsius conversion functions
Exercise 6: Given a test function, write the function
Exercise 7: Evaluate a sum and write a test function
Exercise 8: Write a function for solving \( ax^2 + bx + c =0 \)
Exercise 9: Implement the sum function
Exercise 10: Compute a polynomial via a product
Exercise 11: Integrate a function by the Trapezoidal rule
Exercise 12: Derive the general Midpoint integration rule
Exercise 13: Make an adaptive Trapezoidal rule
Exercise 14: Simulate a program by hand
Exercise 15: Debug a given test function
Exercise 16: Compute the area of an arbitrary triangle
Exercise 17: Compute the length of a path
Exercise 18: Approximate \( \pi \)
Exercise 19: Compute the area of a polygon
Exercise 20: Write functions
Exercise 21: Approximate a function by a sum of sines
Exercise 22: Implement a Gaussian function
Exercise 23: Wrap a formula in a function
Exercise 24: Write a function for numerical differentiation
Exercise 25: Implement the factorial function
Exercise 26: Compute velocity and acceleration from 1D position data
Exercise 27: Find the max and min values of a function
Exercise 28: Find the max and min elements in a list
Exercise 29: Implement the Heaviside function
Exercise 30: Implement a smoothed Heaviside function
Exercise 31: Implement an indicator function
Exercise 32: Implement a piecewise constant function
Exercise 33: Apply indicator functions
Exercise 34: Test your understanding of branching
Exercise 35: Simulate nested loops by hand
Exercise 36: Rewrite a mathematical function
Exercise 37: Make a table for approximations of \( \cos x \)
Exercise 38: Use None in keyword arguments
Exercise 39: Write a sort function for a list of 4-tuples
Exercise 40: Find prime numbers
Exercise 41: Resolve a problem with a function
Exercise 42: Determine the types of some objects
Exercise 43: Find an error in a program
References
This document introduces two fundamental and extremely useful
concepts in programming: user-defined
functions and branching of program flow, the latter often referred to as
if
tests. The programs associated with the document are found
in the folder src/funcif.