Page 405 - Computer_Science_F5
P. 405

Computer Science  In this example, we have a class  us to  break down  complex tasks into
           named  “MyClass”  that  is  defined  but  smaller, reusable blocks of code.
           does not have any members (attributes  Modules are collections of functions and
           or  methods)  defined  yet.  The  “pass”
                                                     variables that can be imported and used
           statement  is used as a placeholder  to
                                                     in other programs.
          FOR ONLINE READING ONLY
           indicate that the class definition is empty
           for now.                                  Meaning  of function

                                                     A function denotes a labeled  segment
           In both cases, the “pass” statement serves
           as a null operation that does nothing.    of code designed to accomplish a
           It is used when the syntax requires  a    specific task. It accepts  inputs, termed
           statement,  but  no  specific  action  or   parameters or arguments, and generates
           implementation is needed at that point.   outputs, referred to as return values.


           Python functions and modules              Function structure
           Python  functions  and  modules  are      Functions are declared using the “def”
           powerful tools that help in organizing    keyword, followed by the function name
           and  structuring code.  Functions  allow  and parentheses.


           Parameters,  if present,  are listed  within  the  parentheses. The  function’s body is
           indented and encompasses the code executed upon function invocation. There is
           advantages in using functions in Python. The following are advantages of function:
           (a)  Code reusability: Functions can be invoked multiple times, curtailing code
               redundancy and fostering efficiency.
           (b)  Abstraction: Functions shield the implementation details, enabling users to
               concentrate on functionality without requiring knowledge of internal workings.

           The following are some examples of how to write functions:
           (i)  Basic Function:
               def invite(name):
                   print(“Welcome, “ + name + “!”)

               welcome(“Pepe Kale”)  # Output: Welcome, Pepe Kale!

           (ii) Function with return Value:

                def cube(number):
                    return number * number*number
                result = cube(3)
                print(result)  # Output: 9


                                                 396
                                                                for Advanced Secondary Schools



     Computer Science Form 5.indd   396                                                     23/07/2024   12:34
   400   401   402   403   404   405   406   407   408   409   410