FUNCTIONS

 Program Routines (Functions):

  • Programs are divided into manageable pieces called program routines or routines.
  • This division is a form of abstraction that allows a higher-level, less detailed perspective of a system.
  • Routines enable code reuse, where you can use existing routines instead of writing new code for similar tasks.
  • This promotes efficiency and reduces redundancy in coding.

What Is a Function Routine?

  • A routine is a named group of instructions performing some tasks.
  • A routine can be invoked (called) as many times as needed in a given program, as shown in Figure.
  • When a routine terminates, execution automatically returns to the point from which it was called. Such routines may be predefined in the programming language or designed and implemented by the programmer.
  • A function is Python’s version of a program routine.

Function Defining

The structure of a function definition is

  • The first line of a function definition is the function header.
  • The function name is followed by a comma-separated (possibly empty) list of identifiers (n1, n2, n3) called formal parameters, or simply “parameters.”
  • Following the parameter list is a colon ( : ).
  • Following the function header is the body of the function, a suite (program block) containing the function’s instructions.
  • As with all suites, the statements must be indented at the same level, relative to the function header.
  • The number of items in a parameter list indicates the number of values that must be passed to the function, called actual arguments (or simply “arguments”), such as the variables num1, num2, and num3 below.
  • Functions are generally defined at the top of a program. However, every function must be defined before it is called.
  • Actual arguments, or simply “arguments,” are the values passed to functions to be operated on.
  • Formal parameters, or simply “parameters,” are the “placeholder” names for the arguments passed.