0% found this document useful (0 votes)
20 views19 pages

Chapter 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views19 pages

Chapter 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

4

SUBPROGRAMS AND PARAMETER


PASSING
Subprogram
A subprogram is a named block of code that performs a specific task, possibly acting upon a set of values
given to it, or parameters, and possibly returning a single value.

 Each subprogram has a single entry point i.e. a starting point.


 Each subprogram can have one or more exit points
 A subprogram call is an explicit request that the subprogram be executed.
 When a subprogram is called, the calling program is suspended during execution of the called subprogram.
 Control always returns to the caller when the called subprogram’s execution terminates.
 There are functions that come pre-packaged with programming languages. These are called
inbuilt functions. Users can also create their own user defined functions specifying its actions.
Terminologies
 A subprogram definition describes the interface to and the actions of the subprogram abstraction.
 The header is the first part of the definition, including the name, the kind of subprogram, and the formal
parameters.
 The parameter profile (also signature) of a subprogram is the number, order, and types of its parameters
 Parameters are variables/ values passed to a subprogram. A formal parameter is a dummy variable listed
in the subprogram header and used in the subprogram while an actual parameter represents a value or
address used in the subprogram call statement
Python: Functions and Procedures
Subprograms in python are called functions. The keyword “def” is used to create a named function.

1 >>> def greet(name) :


2 >>> print “How are you? ”+name

definition keyword function body parameter function name

Python provides some out-of-the-box built-in functions for performing some common programming tasks called.
Some common functions are :int(), float(), str(), type(), bool(), len(), chr(), min(), max(), range(), hex(), bin(),
abs(), ord(), pow(), raw_input(), sum(), format(), cmp(), dir(), oct(), round(), print()
Python also allows programmers to define user-defined functions.
 perform a task or set of tasks
 no return a value
 has a function name and may have zero or more parameters
Python: Functions and Procedures
Built in Functions User Defined Functions
1 >>> len("Technology") 1 def print1to10():
2 10 2 for i in range(1,11):
3 >>> chr(65) 3 print i,
4 'A' 4
5 >>> ord('B') 5 # to call the function
6 66 6 print1to10()
7 >>> range(1,10) 7
8 [1, 2, 3, 4, 5, 6, 7, 8, 9] >>>
9 >>> range (1,20, 3) 8 1 2 3 4 5 6 7 8 9 10
10 [1, 4, 7, 10, 13, 16, 19]
11 >>> range (20,1,-5)
12 [20, 15, 10, 5]
13 >>> sum([3,2],0)
14 5
15 >>> sum(range(1,5), 0)
16 10
17 >>> round(0.89377,3)
18 0.894
Python: Parameter Passing
Functions can also accept values to be used as part as their execution, such values are stored in
variables. The variables are called parameters. Python has four mechanisms for passing parameters

 Normal parameters: Functions can accept values of ay data type i.e. int, float, string, list, tuples etc.
as parameters.

1 def findAverage(num1, num2):


2 ‘’’A function to calculate the average of numbers ’’’
3 average=(num1+num2) / 2
4 print “average is “, average

5 #Calling this function:


6 findAverage(4,8)
7 >>>
8 Average is 6
Python: Parameter Passing
 Parameters with default values: Functions can have optional parameters, also called default parameters.
Default parameters are parameters, which don't have to be given, if the function is called. In this case, the
default values are used.

1 def findAverage(num1, num2=5):


2 ‘’’A function to calculate the average of numbers ’’’
3 average=(num1+num2) / 2
4 print “average is “, average

5 #Calling this function:


6 findAverage(4,8)
7 findAverage(9) #the default value for num2 is used
8 >>>
9 Average is 6
10 Average is 7
Python: Parameter Passing
 Parameter list (*args): There are many situations in programming, in which the exact number of necessary
parameters cannot be determined beforehand. Python uses tuple references. An asterisk "*" is used in front of
the last parameter name to denote it.
1 def findAverage(*num):
2 ‘’’A function to calculate the average of numbers ’’’
3 sum=0
4 if len(num)==0:
5
6 return 0
7 else:
8 for number in num:
9 sum+=number
10 average=sum/len(num)
11 print “average is “, average
12 #Calling this function:
13 findAverage(4,8,4,6,3,2,5,5,8)
findAverage(4,7,8,4,3)
>>> Average is 5
Python: Parameter Passing
 Keyword parameters (**kwargs): Using keyword parameters is an alternative way to make function
calls. The definition of the function doesn't change. Keyword parameters can only be those, which are
not used as positional arguments.

1 def findAverage(num1, num2, num=3, num4=9):


2 ‘’’A function to calculate the average of numbers ’’’
3 average=(num1+ num2+ num3+ num4) / 4
4 print “average is “, average

5 #Calling this function:


6 findAverage(3,5)
7 findAverage(8,7, num4=10) #the default value for num3 is used
8 >>>
9 Average is 5
10 Average is 7
Python: Return Statement and Lambda
There result of the computation in a subprogram might be needed in the calling program. The “return”
statement is used to return values from a function.
1 def findAverage(num1, num2):
2 ‘’’A function to calculate the average of numbers ’’’
3 average=(num1+ num2+ num3+ num4) / 2
4 return average

5 #Calling this function:


6 vg=findAverage(2,5)
7 print “the mean of the numbers is”, avg
8 >>> The mean of the numbers is 6

There are special functions in Python called “lambda”. They are functions that have no name (i.e. anonymous),
contain only expressions and no statements and occupy only one line. They are convenient to use. A lambda can
take multiple arguments and can return (like a function) multiple values

1 determinant = lambda a, b, c: (b ** 2) + (4*a*c)


2 print determinant(4, 5, 6)
3 >>> 281
PHP: Functions
In PHP, functions are defined using the “function” keyword. The function name can be any string that starts with a
letter or underscore followed by zero or more letters, underscores, and digits.

Function names are case-insensitive; that is, you can call the sin() function as sin(1), SIN(1), SiN(1), and so on,
because all these names refer to the same function. By convention, built-in PHP functions are called with all
lowercase.

1 <?php
2 function findAverage(){
3 $average=0;
4 echo “average is “, $average;
5 }
6 ?>
PHP: Parameter Passing
In PHP, There are several kinds of parameters

 Default parameters: To specify a default parameter, assign the parameter value in the function
declaration. The value assigned to a parameter as a default value cannot be a complex expression; it
can only be a scalar value.

1 <?php
2 function findAverage($num1, $num2, $num3=7){
3 $average=($num1 + $num2+$num3)/3;
4 return $average;
5 }
6 ?>
PHP: Parameter Passing
 Variable Parameters: A function may require a variable number of arguments. To declare a function with a
variable number of arguments, leave out the parameter block entirely

1 <?php
2 function findAverage(){
3 if (func_num_args() == 0) {
4 return 0;
5 }
6 else {
$sum = 0;
for ($i = 0; $i<func_num_args(); $i++) {
$sum += func_get_arg($i);
}
$average=$sum/func_num_args();
return $average;
}
}
?>
PHP: Parameter Passing
PHP provides three functions you can use in the function to retrieve the parameters passed to it.
 func_get_args() returns an array of all parameters provided to the function;
 func_num_args() returns the number of parameters provided to the function;
 func_get_arg() returns a specific argument from the parameters.

For example:
$array = func_get_args();
$count = func_num_args();
$value = func_get_arg(argument_number);
PHP: Parameter Passing
 Missing Parameters: PHP allows the passing of any number of arguments to the function. Any parameters the
function expects that are not passed to it remain unset, and a warning is issued for each of them:

1 <?php
2 function findAverage($num1, $num2, $num3=7){
3 $average=($num1 + $num2+$num3)/3
4 return $average
5 }
6 ?>
PHP: Parameter Passing
Passing Parameters by Value
This means the value of the parameter is copied into the function i.e. the function has access to a copy of the value
not the original .The function is evaluated, and the resulting value is assigned to the appropriate variable in the
function. In all of the examples so far, we’ve been passing arguments by value.

Passing Parameters by Reference


Passing by reference gives a function direct access to a variable. you indicate that a particular argument of a
function will be passed by reference by preceding the variable name in the parameter list with an ampersand (&).

1 <?php
2 function findAverage(&$num1, &$num2,){
3 $average=($num1 + $num2)/2
4 return $average
5 }
6 ?>
PHP: Parameter Passing
To return a value by reference, both declare the function with an & before its name and when assigning the
returned value to a variable:

1 <?php
2 function &findAverage($num1, $num2, $num3){
3 $average=($num1 + $num2+$num3)/3
4 return $average
5 }
6 ?>
PHP: Anonymous Functions
PHP allows the definition of localized and temporary functions. Such functions are called anonymous functions or
closure. It is defined using the normal function definition syntax, but assign it is then assigned to a variable or pass
it directly.

1 <?php
2 function findAverage($num1, $num2, $num3, function(){ return
3 $sum=$num1 + $num2+$num3)}){
4 $average=($num1 + $num2+$num3)/3
5 return $average
6 }
?>
Python and PHP

Python PHP
Function Keyword def function
Parameter Passing pass by reference pass by value, pass by reference

Types of parameter normal, default value, parameter Variable, default, missing


list, keyword
Special function Lambda Anonymous function

You might also like