HCI 4. Functions
Uploaded by adrianwang2003 · 28 May 2024
Preview
Text from the first pagesHwa Chong Institution H2 Computing 1 4 Functions Learning Outcome Function is an abstraction mechanisms that hides details and allows us to view many things as just one thing. We can use functions to organize our codes more effectively. 4.1 Advantage of Functions Functions serve as abstraction mechanisms by eliminating redundant, or repetitious, code. Functions serve as abstraction mechanisms by hiding complicated details. For example, consider the previous sum function. The idea of summing a range of numbers is simple; the code for computing a summation is not. A function call expresses the idea of a process to the programm er without forcing him/her to wade through the complex code that realizes that idea Functions Support General Methods with Systematic Variations - An algorithm is a general method for solving a class of problems - The individual problems that make up a class of problems are kn own as problem instances - Algorithms should be general enough to provide a solution to many problem instances - A function should provide a general method with systematic variations Programming Elements and Contructs Use functions and procedures to modularise problem into chunks of code Understand the concept of recursion Trace the steps and list the results of recursive and non-recursive programs
Hwa Chong Institution H2 Computing 2 Functions Support the Division of Labor - In a well-organized system, each part does its own job in colla borating to achieve a common goal - In a computer program, functions can enforce a division of labor - Each function should perform a single coherent task - Each of the tasks required by a system can be assigned to a function, including the tasks of managing or coordinating the use of other functions 4.2 Problem Solving with Top-Down Design Top-down design starts with a global view of the entire problem and breaks the problem into smaller, more manageable subproblems, process known as problem decomposition As each subproblem is isolated, its solution is assigned to a function As functions are developed to solve subproblems, solution to overall problem is gradually filled out, process known as stepwise refinement 4.3 Define Simple Functions 4.3.1 The Syntax of Simple Function Definitions A function can be defined in a Python shell, but it is more convenient to define it in an IDLE window. Definition of a function consists of header and body. Syntax of a function definition: Docstring contains information about what the function does; to display, enter help(square) 4.3.2 Parameters and Arguments A parameter is the name used in the function definition for an argument that is passed to the function when it is called. Arguments provide the function’s caller with the means of transmitting information to the function. The number and positions of arguments of a function call usually match the number and positions of the parameters in the definition. Some functions expect no arguments. They are defined with no parameters .
Hwa Chong Institution H2 Computing 3 Programmer can specify optional arguments with default values in any function definition: Following the required arguments are one or more default or keyword arguments. When function is called with these arguments, default values are overridden by caller’s values. The default arguments that follow can be supplied in two ways: By position By keyword 4.3.3 The return Statement Place a return statement at each exit point of a function when function should explicitly return a value. Syntax:
Hwa Chong Institution H2 Computing 4 If a function contains no return statement, Python transfers cont rol to the caller after the la st statement in the function’s body is executed. The special value None is automatically returned. 4.3.4 Functions with Multiple Return Variables A function can return multiple values. For example, the code below returns both sum and average. 4.3.5 Boolean Functions A Boolean function usually tests its argument for the presence or absence of some property. It returns True if property is present; False otherwise For example, the function odd below tests if a number is odd. 4.3.6 Defining a main Function main serves as the entry point for a script. It usually expects no arguments and returns no value. Definition of main and other functions can appear in no particular order in the script, as long as main is called at the end of the script. Script can be run from IDLE, imported into the shell, or run from a terminal command prompt
Hwa Chong Institution H2 Computing 5 4.4 Recursive Functions In a recursive subprogram, the body of the subprogram contains a call to itself. Recursion is used when the original task can be reduced to a simpler version of itself. The idea is that after a number of successive reductions, the reduced problem will eventually be simple enough to be solved directly, and its solution will be used to piece together a solution to the original problem. As an illustration, recall that for n, a positive integer, n! is equal to the product of the first n integers. For example, 4! = 4 * 3 * 2 * 1 = 24 5! = 5 * 4 * 3 * 2 * 1 = 120 1! is defined as 1. Note that for any positive n, n! = n * (n-1)! Thus, finding n! can be reduced to the similar but simpler task of finding (n-1)!. 4.4.1 Defining a Recursive Function with Terminal Case Remember that whenever a subprogram call has been completed, co ntrol is returned to the point at which the subprogram was called. The same rule applies to recursive calls.
Hwa Chong Institution H2 Computing 6 Terminal Case I n o r d e r t h a t s u c c e s s i v e r e c u r s i v e c a l l s n o t c o n t i n u e i n d e f i n i tely, the body of a recursive subprogram should include at least one terminal case – a case t hat contains no further calls to the recursive subprogram (As you will see, terminal cases are similar to loop exit conditions.) In the following example, the terminal case is n = 1. Example (Recursive Factorial Function) Here is the output to compute 4! enter a positive integer 4 4 factorial is 24 When this program is run to compute 4!, there will be four calls to the recursive function FACT. The first call is to FACT(4) from the main body. This call cannot be completed immediately since FACT(4) calls FACT(3), which calls FACT(2), which calls FACT(1). The call to FACT(1) is the first call that can be completed. Then the computer winds back up and assigns FACT the value 1. That value is sent to the place where FACT(1) was called. Then the call of FACT(2) is completed and the value 2 is sent to the place where FACT(2) was called. Then the call of FACT(3) is completed, and the value 6 is sent to the place where FACT(3) was called. Finally, the original call of FACT(4) is completed. def FACT(n): if n==1: return 1 else: return n * FACT(n-1) def main(): n = int(input(“ener a positive integer: “)) print (n, “ factorial is “, FACT(n)) main()
Hwa Chong Institution H2 Computing 7 Here is the trace diagram. C refers to call, and R refers to Return. The following example takes a further look at "winding back up" to finish unfinished calls. The output for JOB (4) will be 4 h i 3 h i 2 h i n = 1 GO BACK 2 b y e 3 b y e 4 b y e def JOB (n): if n == 1: // terminal case print(“n = 1 GO BACK”) else: // recursive step print(n, “ hi”) JOB (n-1) print(n, “ bye”) FACT = 24 R4 result = FACT (4) C1 n = 4 FACT = 4 * FACT(3) FACT = 3
Content continues in the PDF. Download PDF
Related notes
- NYJC 2026 Prelim P2Exam Papers · 2026
- NYJC 2026 Prelim P1Exam Papers · 2026
- DHS 2026 Y6 H2 Computing Prelim Paper 2_finalExam Papers · 2026
- ACJC 2026 JC2 Computing Prelim Paper 2 (Practical)Exam Papers · 2026
- 2026_NJC Prelim_Computing_P2.pdfExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P2_finalExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P1_markschemeExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P1_finalExam Papers · 2026
- 2026 ACJC Prelim Computing Paper 2Exam Papers · 2026
- 2024 ACJC Computing PromoExam Papers · 2024
- 2023 ACJC Promo QPExam Papers · 2023
- 2022 ACJC Computing Promo Paper 2Exam Papers · 2022
- See all H2 Computing notes

