--- slideOptions: theme: white --- # Chapter 6 - Function and Testing ###### tags: `Computer programming` --- ## Learning objectives By the end of this chapter, you should able to: 1. Describe the concept of a function 2. Declare, define and call a function in Python with or without return value 3. Separate a program with several functions 4. List out test cases for a program fragment 5. Identify the boundary data ## Introduction - function in mathematics Function is widely used in daily lives, especially in both mathematics and computer programming. This concept is similar in both fields. In mathematics, function, like a machine, accepts the input and then returns one and only one value as output. ![](https://i.imgur.com/8rtmCFb.png) The following shows a function $f(x)$ that accepts an input x and then gives out an output $x+2$. ![](https://i.imgur.com/TFA04uN.png) | _$x$_ | -4 | -2 | 0 | 2 | 10 | | --: | :-: | :-: | :-: | :-: | :-: | | _$f(x)$_ | -2 | 0 | 2 | 4 | 12 | ## Function in Python programming A Python program is built up by _functions_. You can think of a function as a _subprogram_ - a small program inside a program. The basic idea of a function is that we write a sequence of statements and give that sequence a name. The program performs action by calling other functions. ![](https://i.imgur.com/kh69T4U.png) ### Purpose of a function For every function in Python, they must have the following purpose. 1. Accepts zero or more pieces of data 2. Operate on them 3. Return data (usually zero or one piece or data) by _`return` statement_ ### Advantages of using functions There are several advantages to using functions. 1. Understandable and manageable steps by _having good function identifiers_ 2. Reusable codes by calling the functions 3. Can be collected as a library and used by others 4. Protect data within a function ### Designing a structured program There are various modules in a structure program. Each module is designed to do a specific task. In normal circumstances, we use the **main module** as the first module run in the program, the other modules are called by the main module. ![](https://i.imgur.com/lkOWc5T.png) From the above diagram, function a, function b and function c are called by main function. The main function is called the _calling modules_, and function a, function b and function c are called the _called modules_. ## Use of functions in Python ### Introduction In Python, the functions must be **defined** before being called. The following diagram sows an example of defining and calling a function in Python and shows its execution sequence. ![](https://i.imgur.com/2q1HyBY.png) A function can return _at most one value_. The function's value is the value in the expression of the return statement, which also _terminates the function_. A function can be called for its returned value and/or its side effect. ### Function definition The following shows the _syntax_ on function definition. ![](https://i.imgur.com/n1H9clx.png) #### Parameters A function accepts the _formal parameters_ and copies the value to the _actual parameters_. ![](https://i.imgur.com/ru41GXs.png) **Formal parameters** : variables that are declared in the header of the function definition. **Actual parameters** (often called _arguments_): the expressions in the calling statement, Formal and actual parameters _must match exactly in type (if necessary), order and number_. Their names, however, do not need to match. #### Return type Each function should have the _return type_, that is the same as the data type of the return value. Only the functions that return a value can be used in an expression or as a separate statement without any errors. For example, `amt = getQuantity()` `b = sqr(a)` #### Local variables Local variables are the variables that are declared in the function. They have the _local scope_. In other words, they can be used within the function only. ![](https://i.imgur.com/bO1idxQ.png) #### Inter-function communication There are two implementations of passing parameters in common, namely _pass by value_ and _pass by reference_. However, pass by reference is not implemented in Python. ##### Pass by value For _pass by value_, the values of formal parameters are copied from the actual parameters. The value changed in the formal parameter will NOT affect the value of the actual parameters. Below shows an example. ![](https://i.imgur.com/2xWxLWf.png) Sometimes a function needs to return more than one value. This can be done by simply listing more than one expression in the return statement. Below shows a program with a function that computes both the sum and difference of two numbers, and then returns the values to two variables. <iframe src="https://trinket.io/embed/python3/5dbc179928?runOption=run" width="100%" height="250" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> ##### Pass by reference (simulated by pass by assignment or pass by object reference) For _pass by reference_, the actual parameters are used as the formal parameters. The value changed in the formal parameters will also change the value of the actual parameters. There is no implementation of pass by reference in Python. However, we can simulate _pass by reference_ by passing an object to the function. The properties of objects would be discussed in the later topic. For simulating pass by reference, we need to pass the object from the actual parameters. Below shows an example with a list object. ![](https://i.imgur.com/x4d6i2j.png) With _pass by reference_, we can simulate more than one return value by a function. Below shows an example. ![](https://i.imgur.com/2ZEnKhh.png) ##### Return value The calling function receives the result from the called function. The value can be returned by the called function with return statement. ### Function call It is simple to call a function in Python, just type the defined and declared function name with corresponding number of parameters. The actual parameters in a function call do not have to be variables. You can use numbers, expressions or even another calls as actual parameters. ![](https://i.imgur.com/A27mXgd.png) ### Example 1 - Functions without parameters and return value <iframe src="https://trinket.io/embed/python3/c3c1eb2dc7?runOption=run" width="100%" height="175" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>) ### Example 2 - Functions with parameter but without return value ![](https://i.imgur.com/O7fWt1h.png) The function can be called more than once. Below shows an example. <iframe src="https://trinket.io/embed/python3/bf84ca6140?runOption=run" width="100%" height="200" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> ### Example 3 - Function with parameter and return value The following example shows a function that accepts a number (integer) from the formal parameter, and then returns the square of the accepted number. ![](https://i.imgur.com/dPLU87s.png) ## Library In Python, sets of functions and constants are written and collected as a **library** , and ready to be called by the other functions. To use those functions and contants, we need to import the corresponding library(ies). ![](https://i.imgur.com/K9Usyyh.png) Python provides many useful mathematical functions in a special math _library_. The following shows some functions and constants included in the math library. | **Python** | **Mathematics** | **English** | | --- | --- | --- | | pi | $\pi$ | An approximation of $\pi$. | | e | $e$ | An approximation of $e$. | | sqrt(x) | $\sqrt{x}$ | The square root of $x$. | | sin(x) | $\sin{x}$ | The sine of $x$. | | cos(x) | $\cos{x}$ | The cosine of $x$. | | tan(x) | $\tan{x}$ | The tangent of $x$. | | asin(x) | $\arcsin{x}$ | The inverse of sine $x$. | | acos(x) | $\arccos{x}$ | The inverse of cosine $x$. | | atan(x) | $\arctan{x}$ | The inverse of tangent $x$. | | log(x) | $\ln{x}$ | The natural (base $e$) logarithm of $x$. | | log10(x) | $\log\_{10}{x}$ | The common (base 10) logarithm of $x$. | | exp(x) | $e^{x}$ | The exponential of $x$. | | ceil(x) | $\left \lceil{x} \right \rceil$ | The smallest whole number \>= $x$. | | floor(x) | $\left \lfloor{x} \right \rfloor$ | The largest whole number \<= $x$. | ### Example - Calculation of quadratic equation Belows shows a program that can find the solution to a quadratic equation. A quadratic equation has the form $ax^2 + bx + c = 0$. Such an equation has two solutions for the value of $x$ given by the quadratic formula: $$x = \frac{-b \pm \sqrt{b^2-4ac} }{2a}$$ The input to the program will be the values of the coefficients $a$, $b$ and $c$. The outputs are the two values given by the quadratic equation. <iframe src="https://trinket.io/embed/python3/f42693ece9?runOption=run" width="100%" height="300" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> The above program can only accept the numbers that $b^2 - 4ac \>= 0$. If not, error occurs due to `sqrt` function is unable to compute the square root of a negative number, <iframe src="https://trinket.io/embed/python3/e489c5ad61?runOption=run&start=result" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> This problem can be solved by _exception handling_, which will be discussed in a later chapter. ## Scope _Scope_ determines the region of the program in which a defined object it visibles, i.e. the part of the program in which we can use the object's name. Variables are in scope from declaration until the end of their block. It is a poor programming style to reuse identifiers within the same scope. ![](https://i.imgur.com/PeRlCv7.png) ## Unit Testing Every module should be tested before they are integrated into a large program. We called the testing of the modules one by one as using testing. _Unit testing_ is used to test the modules after they are just coded. We have to test the software (or a code segment) by some _test cases_ to test whether the software works correctly. For example, in the specification, the program will check whether the player has input a 4-digit number with no duplicate digits. We may have the following possible test cases. - 1234 - 123 - 21345 - 1231 - 12AB We can examine _equivalence testing_ and _boundary value analysis_. For example, the specifications for a Database Management System (DBMS) state that the product must handle any number of records between 1 and 16383. The range from 1 to 16383 (exclude 1 and 16383) constitutes an equivalence class. ### Equivalence testing Any one member of an _equivalence class_ is as good a test case as any other member of the equivalence class. In our example, we have three different equivalence classes. - Equivalence class 1: Fewer than 1 record - Equivalence class 2: Between 1 and 16383 records - Equivalence class 3: More than 16383 records ![](https://i.imgur.com/qbVBynV.png) If we convert it into a program, decision statement should look like as the following. ```python! if n >= 1 or n < 16383: # do something when the condition is met … else: # do something when the condition is not met ... ``` ### Boundary cases We can also select test cases on or just to one side of the boundary of equivalence classes. For example, the programmer can write the following to test the code segment. ```python! if n > 16383: print("Too many records!") ``` If we first perform equivalence testing and then boundary value analysis, we will have the following seven test cases for input specifications. | **Test Case** | **Number of Records** | **Remarks** | | --- | --- | --- | | #1 | 0 | Member of equivalence class 1 and adjacent to boundary value | | #2 | 1 | Boundary value | | #3 | 2 | Adjacent to boundary value | | #4 | 723 | Member of equivalence class 2 | | #5 | 16382 | Adjacent to boundary value | | #6 | 16383 | Boundary value | | #7 | 16384 | Member of equivalence class 3 and adjacent to boundary value | In short, we should prepare **at least 5 test cases** for this code segment, - Any value that `n < 1` - `n = 1` - Any value that `n > 1 and n < 16383` - `n = 16383` - `n > 16383` ## Chapter Summary - A function is a kind of subprogram. Programmers use functions to reduce code duplication and to help structure or modularise programs. - Once a function is defined, it may be called multiple times from many different places in a program. - Parameters allow functions to have changeable parts. The parameters appearing in the function definition are called formal parameters, and the expressions appearing in a function call are known as actual parameters. - A call to a function initiates a four-step process: - The calling program is suspended. - The values of actual parameters are assigned to the formal parameters. - The body of the function is executed. - Control returns immediately following the function call in the calling program. The value returned by the function is used as the expression result. - The scope of a variable is the area of the program where it may be referenced. Formal parameters and other variables inside function definition are local to the functions. Local variables are distinct from variables of the same name that may be used elsewhere in the program. - Functions can communicate information back to the caller through return values. In Python, functions may return multiple values. - Python passes parameters by value. ## Exercise 1. Programmers rarely define their own functions. A. True B. False 2. A function may only be called at one place in a program. A. True B. False 3. Information can be passed into a function through parameters. A. True B. False 4. Every Python function returns some values. A. True B. False 5. In Python, some parameters are passed by reference. A. True B. False 6. In Python, a function can return only one value. A. True B. False 7. Python function can never modify a parameter. A. True B. False 8. One reason to use functions is to reduce code duplication. A. True B. False 9. Variables defined in a function are local to that function. A. True B. False 10. It's a bad idea to define new functions if it makes a program longer. A. True B. False 11. A Python function definition begins with A. def B. define C. function D. defun 12. A function can send output back to the program with a(n) A. return B. print C. assignment D. SASE 13. In Python, actual parameters are passed to functions A. by value B. by reference C. at random D. by networking 14. If a function returns a value, it should generally be called from A. an expression B. a different program C. main D. a cell phone 15. A function with no return statement returns A. nothing B. its parameters C. its variables D. None 16. Consider this very simple function: ```python! def cube(x): answer = x \* x \* x return answer ``` 1. What does this function do? 2. Show how a program could use this function to print the value of $y^3$, assuming $y$ is a variable. 3. Here is a fragment of a program that uses this function: ```python! answer = 4 result = cube(3) print(answer, result) ``` The output from this fragment is 4 27. Explain why the output is not 27 27, even though cube seems to change the value of answer to 27. ## Programming Exercise ### Exercise 1 Rewrite Ch. 5 Exercise 7 by using a function. A positive whole number $n > 2$ is prime if no number between 2 and $\sqrt{n}$ (inclusive) evenly divides $n$. Write a program to find every prime number less than or equal to *n*. Define a function to determine if the number is a prime number. You may modify the follow program. ```python= #Programmer: Yip Pak Ming #Date: 26/10/2022 #Time: 12:00 # Step 1: Input the value num = int(input("Please input a value: ")) prime = True # Step 2: set the range of 2 to num for i in range(2, num): # Step 3: Determine whether it can be divided by i if num % i == 0: prime = False # Step 4: Print the result if prime: print("It is a prime number.") else: print("It is not a prime number.") ``` ### Exercise 2 The formula for converting Celsius temperatures to Fahrenheit is $$F=32+C \frac{180.0}{100.0}$$ Write a program that asks the user to enter temperature reading in Celsius and then prints the equivalent Fahrenheit value. It then asks the user to enter a Fahrenheit value and prints out the equivalent Celsius. Provide separate functions as in the following diagram. ![](https://i.imgur.com/IuLveZQ.png) ### Exercise 3 Write a function to compute the perimeter and area of a right triangle when given the length of the two sides (a and b). The following formulas may be helpful. $$c^2=a^2+b^2$$ $$Area = 0.5 \times (a \times b)$$ ### Exercise 4 Write a program that includes a function named `rounding`. The function takes two parameters, a float named number and an integer place. The function rounds the number _in decimal places_ and returns that value. The main function should read a float and an integer, and then call the function and print out the result. Example: ``` Enter a number: 12.3456 Rounding to how many decimal places? 3 The result is 12.346 ``` ### Exercise 5 Write a program to print the lyrics of the song "Old MacDonald." Your program should print the lyrics for five different animals, similar to the example verse below. ``` Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! And on that farm he had a cow, Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there. Here a moo, there a moo, everywhere a moo, moo. Old MacDonald had a farm, Ee-igh, Ee-igh, Oh! ``` ### Exercise 6 Write definitions for the following two functions: `sumN(n)` returns the sum of the first $n$ natural numbers. `sumNCubes(n)` returns the sum of the cubes of the first $n$ natural numbers. Then use these functions in a program that prompts a user for an $n$ and prints out the sum of the first $n$ natural numbers and the sum of the cubes of the first $n$ natural numbers.