Ho Hei, Herman Yeung
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- 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.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully