Python Functions 2

User Defined Functions

For any medium-size to large-size program, user-defined functions are almost essential.  These functions make your program shorter, concise, and easy to understand.

Below is how to define a User-Defined Function:

>>> def function_name():

First Line of User-Defined Function

The user-defined function’s first line is as above. The first word in a user-defined function is always def.

Note that def is Python Keyword. The list of Python keywords is in Appendix.

The second word of the first line in a user-defined function is the function’s name (identifier). You, as a programmer, can choose any name you like for the identifier name, except any reserved words (keywords).

The identifier is immediately followed by a list of arguments separated by commas.  The arguments list is enclosed in parentheses ().  This is the data that the calling program passes to the function to do the computation on.

Note there must be a colon (:) after the closing parenthesis.

The Second Line: Body of the User-Defined Function Code

From the second line onward is the body of the function

The body is comprised of statements that define the function’s functionality. These statements describe the computations that the function is supposed to do.  

When Python sees the colon at the end of the first line, all the following lines of code (the body) are automatically indented with respect to the first line. (Do not backspace the indent).

End of the User-Defined Function

At the end of the function’s body is the return statement that returns the computed value back to the calling program. The return statement exits the function and causes the control of the program to be returned back to the calling program, where the function was called from. The syntax of the return statement is below:

>>> return function_name ()

The variable name where you want to save the computed value returned by the function is written within the parenthesis of the return statement.

As an example, if the function’s name is “prime_number” and you would like to save the function’s computed result in the variable “result”, you would write the following statement:

>>> return prime_number(result)

In the above statement, the value returned by the function is stored in the variable “result”.

Some functions return a value; while other functions may not return any value. If a function does not return a value, the return statement may be omitted. Thus, the return() statement is optional.

Rules for Writing User-Defined Functions

To recap, the following are the rules for defining functions.

  1. Functions must start with the keyword def
  2. The calling program calls the function by using the function’s name and providing an argument or a list of arguments enclosed in parentheses separated by commas.
  3. The function will perform the computations and return a value to the calling program at the place where the function was called from.
  4. A return statement at the end of the body is required if you want the computed value to be saved in a variable.
  5. If you use a print() statement without a return statement, the computed value is displayed on the monitor but is not saved.
  6. The function does not necessarily return a value.  In this case, the return statement may be omitted.
  7. The function code must be placed in the program before the place where you want to call the function from.

Passing the Arguments

Functions are called by the main program to do a computation and return the results of the computations to the main program. The main program passes the argument(s) to the function. The arguments passed by the main (calling) program are used by the function to perform the computations as per the function’s body code. The function returns the computed result back to the calling program.

Let us explain the use of the function by a simple program.

The program below defines a function, named “sum”. The function “sum” computes the sum of three number variables, a, b, and c. The main program calls the function “sum” by using the name “sum” and providing arguments 7, 8, and 9 in the parenthesis.

PROGRAM EXAMPLE: DECLARING AND PASSING ARGUMENTS IN FUNCTIONS
>>> # Example of User Defined Function
>>> def sum(a,b,c):   # Declare the parameters a, b, and c
	print('The addition of a+b+c =', a+b+c) # Body of function

	
>>> # Main program
>>> # Call the function 'sum'
>>> sum(7,8,9)   # Pass the arguments 7, 8, 9 that replace parameters a, b, c
The addition of a+b+c = 24  # Value returned by the function = 24.

The function may be passed no argument, one argument, or multiple arguments. Let us write program examples of each of these cases.

Functions With No Arguments

Some functions have no parameters, so the main program’s call does not have any text within the parentheses. 

To lighten the discussion, let us do an example of a function with no argument with a silly joke.

PROGRAM EXAMPLE: FUNCTION WITH NO ARGUMENT
>>> # Example of function with no arguments
>>> def joke():
	print('What is the opposite of blue, but not heavy?')
	print('Answer: Light blue')

	
>>> # Main program
>>> # Now call the function 'joke'.
>>> joke()   # Function call has no arguments.
What is the opposite of blue, but not heavy?
Answer: Light blue
>>>

User Defined Function with One Argument

In the program example below, we will pass one argument to the function.

In the program below, we define a function “square”.

This function can be called by the main program to compute the square of any number by passing the number to be squared as the argument in the parenthesis of the function call.

PROGRAM EXAMPLE: FUNCTION WITH ONE ARGUMENT
>>> # Function with one parameter
>>> def square (x):   # Define a function ‘square’ and declare a parameter ‘x’.
	sq = x*x	
	print('The square of number ', x, 'is = ', sq)	# Body of the function
	
>>> # Main Program starts here.
>>> # Call the function square() and pass an argument.
>>> square(3)    # Argument in the function call is '3'.
The square of number  3 is =  9 # Value returned by function
>>> square(5)    # Argument in the function call is '5'.
The square of number  5 is =  25 # Value returned by function.
>>> square(9)    # Argument in the function call is '9'.
The square of number  9 is =  81 # Value returned by function.
>>> 

In the above example, by passing different arguments to the function, the main program can have the function compute the square of any number.

You can use the range() function in the body of the user-defined function. This function will compute the square of a list of numbers. 

Type the statement below in the body of the function

range (1, 101, 2)

This function will return the square of all odd numbers from 1 to 99. Try it to see if this works for you.

User Defined Functions With Two Arguments

Now we will define a function with two arguments.

For our example, we will use measurements of the American football field to define the function with two parameters.

The rectangular field of play of the American football game measures 100 yards (91.44 m) long between the goal lines, and 160 feet (48.8 m) (53 1⁄3 yards) wide. The program below computes the football field length and width in meters. The main program passes two arguments to the function for parameters named, “length” and “width”.

The table below provides the conversion factors between the US and metric measurement units. The program will use this conversion table.

US Units / Metric Units Conversion for Length

LENGTH UNITS
One mile 1.60934 kilometerOne kilometer0.621371 miles
1  yard (yd)0.9144  meter1 meter (m)1.0936 yards
1 foot (ft)0.3048 meter  
LENGTH UNITS
PROGRAM EXAMPLE: FUNCTION WITH TWO ARGUMENTS
>>> # Example of function with two parameters
>>> # Convert football field dimensions from yards to meters.
>>> # Define a function 'football field' 
>>> # and declare parameters 'length' and 'width'.
>>> def football_field(length, width):
	length_meters = length * 0.9144 # Body of function.
	width_meters = width * 0.9144
	print('''The football field length in meters =''', length_meters, '''
And the width in meters =''', width_meters)

	
>>> # Below is the main program (calling program)
>>> # Call function ‘football_field’
>>> # Pass the arguments length = ‘100’ and width =‘53.333’
>>> football_field(100, 53.333) 
The football field length in meters =  91.44 # Values returned
And the width in meters =  48.7676952        # Values returned
>>> 
>>>
>>> # Using named parameters, we can call the function 
>>> # and specify parameter name and its value
>>> # Different way to pass the arguments by using name and value.
>>> football_field(length = 100, width = 53.3333)
The football field length in meters =  91.44 
And the width in meters =  48.76796952
>>> 

User Defined Functions With Four Arguments

Now that we know how to define a function with none, one, and two parameters, let us do an example program declaring and passing four arguments.

We will do the example of after_school_activity that we discussed earlier in this chapter.

In this example, we define a function called “after_school_activity” and declare four parameters:

  • day_of_week
  • sport
  • dinner
  • home_work

The body of the function program has just one statement – a print statement.

The main program (calling program) calls the function “after_school_activity” and passes the four arguments.  If on Monday, the after-school sport is soccer, the dinner is pizza, and you do Math homework, the first call will pass the following four arguments to the function “after_school_activity”:

PARAMETERPASS THE FOLLOWING ARGUMENTS
day_of weekMonday
sportsoccer
dinnerpizza
Home_workmath
Pass Four Arguments

Similar arguments are passed for each day of the week. Read this program and see if you understand it. You can copy and run it on the Python shell.

PROGRAM EXAMPLE: FUNCTION WITH FOUR ARGUMENTS
>>> # Define the function ‘after_school_activity’
>>> def after_school_activity( day_of_week, sport, dinner, home_work):
	print(day_of_week, ' :play ', sport, ' have ', dinner, ' do ', home_work)
>>> # Below is the Main Program (Calling Program)
>>> # Now call function 'after_school_activity' and pass arguments for Monday.
>>> after_school_activity('Monday','soccer','pizza','math')
Monday : play  soccer , have  pizza , do  math # Values returned from function.
>>> # Call the function ‘after_school_activity’ for Tuesday
>>> after_school_activity('Tuesday','basketball','mac&cheese','history')
Tuesday : play  basketball , have  mac&cheese , do  history
>>>
>>>  # Call the function ‘after_school_activity’ for Wednesday.
>>> after_school_activity('Wednesday','tennis','lasagna','science')
Wednesday : play  tennis , have  lasagna , do  science
>>>
>>> # Call the function ‘after_school_activity’ for Thursday
>>> after_school_activity('Thursday','baseball','sandwich','social studies')
Thursday : play  baseball , have  sandwich , do  social studies
>>>
>>> # Call the function ‘after_school_activity’ for Friday
>>> after_school_activity('Friday','softball','Taco','geography')
Friday : play  softball , have  Taco , do  geography
>>> 

Function With Return Statement

The function examples in the previous sections print the result of the computation when called by the calling program. The computation result is not saved to a variable for subsequent use by the program.

Let us see how we can save the computed value, then print it. Functions that return values can be used in expressions.

Let us use the same “add” function for this example.

PROGRAM EXAMPLE: FUNCTIONS WITH RETURN STATEMENT
>>> # Function with return example
>>> # Define function named ‘add’ and declare the parameters x, and y.
>>> def add(x,y):
	z = x + y    # Body of function
	return z

>>> # Main program
>>> # Call the function ‘add’
>>> add(2,3)    # Pass the arguments x = 2 and y = 3.
5  # Value returned by the function is stored in variable z.
>>> add(3,4) + add(4,5)
16
>>>

Let us do another example to explain the ‘return’ statement. We will use the “football_field” function with the return statement to show how the return statement works.

PROGRAM EXAMPLE: FUNCTION WITH RETURN – EXAMPLE 2
>>> # Function with another return example
>>> # Define a function called ‘footbal_field’.
>>> # And declare parameters ‘length’, and ‘width’.
>>> def football_field(length, width):
	perimeter = 2 * (length + width)
	area = length * width    # Body of function
	return(perimeter, area)

>>> # Main Program
>>> # Now call the function 'football_field'
>>> # Pass the arguments length =100; width = 53.333
>>> football_field(100, 53.333)  
(306.666, 5333.3)    # Values returned by the function
>>>

The function returns the value to the main program.

perimeter = 306.666 and area = 5333.3.

Functions Combined With Range() Function

So far, we have learned functions that compute and return just one result. If we want the function to perform many computations and return many values back to the main program, we can use the range() function.

We discussed the range() function in Python Function 1 Chapter.  Let’s use the range() function to define a function to compute and return many computation results.

Suppose you get a math assignment from school to find the squares of all numbers from 1 to 5.  You already know the answer to this assignment. Let us see how Python can solve this problem using a user-defined function.

PROGRAM EXAMPLE: FUNCTION USING range() FUNCTION
>>> # Function using range()
>>> # Define function called square(). Note the function is defined with no parameters.
>>> # We use range() function to calculate squares of numbers from 1 to 5
>>> def square():
	for x in range(1,6):
		print('x = %s; x_square = %s' %(x, x*x))    #Body of function.

		
>>> # Main Program. Call the function 'square()'.
>>> square()
x = 1; x_square = 1
x = 2; x_square = 4
x = 3; x_square = 9
x = 4; x_square = 16
x = 5; x_square = 25
>>>
Verified by MonsterInsights