登录

Procedures and functions

Defining and calling Procedures

A procedure with no parameters is defined as follows:

PROCEDURE <identifier>
    <statements>
ENDPROCEDURE

A procedure with parameters is defined as follows:

PROCEDURE <identifier>(<param1>:<datatype>, <param2>:<datatype>...)
    <statements>
ENDPROCEDURE

The <identifier> is the identifier used to call the procedure. Where used, param1, param2, etc. are identifiers for the parameters of the procedure. These will be used as variables in the statements of the procedure. Procedures should be called as follows:

CALL <identifier>
CALL <identifier>(Value1,Value2...)

These calls are complete program statements.

When parameters are used, Value1, Value2... must be of the correct data type as in the definition of the procedure.

When the procedure is called, control is passed to the procedure. If there are any parameters, these are substituted by their values, and the statements in the procedure are executed. Control is then returned to the line that follows the procedure call.

No procedure

Defining and calling functions

Functions operate in a similar way to procedures, except that in addition they return a single value to the point at which they are called. Their definition includes the data type of the value returned.

A function with no parameters is defined as follows:

FUNCTION <identifier> RETURNS <data type>
   <statements>
ENDFUNCTION

A function with parameters is defined as follows:

FUNCTION <identifier>(<param1>:<datatype>, <param2>:<datatype>...) RETURNS <data type>
    <statements>
ENDFUNCTION

The keyword RETURN is used as one of the statements within the body of the function to specify the value to be returned. Normally, this will be the last statement in the function definition.

Because a function returns a value that is used when the function is called, function calls are not complete program statements. The keyword CALL should not be used when calling a function. Functions should only be called as part of an expression. When the RETURN statement is executed, the value returned replaces the function call in the expression and the expression is then evaluated.

Example – definition and use of a function

FUNCTION SumSquare(Number1:INTEGER, Number2:INTEGER) RETURNS INTEGER
    RETURN Number1 * Number1 + Number2 * Number2
ENDFUNCTION
OUTPUT "Sum of squares = ", SumSquare(10, 20)

def {function}({parameters}):
	{statements}
	return {value}

def factorial(number):
	result = 1
	for i in range(1, number + 1):
		result = result * i
	return result
f1 = factorial(5)
f2 = factorial(10)
print(f1)
print(f2)

登录