Functions are useful when we have a section of code that we need to use over and over again. Putting the section of code in the form of a function allows the reuse of code by calling the function. Functions are provided with input values, they then perform
a computation using the input and, finally, return values as the function output. Python has many built-in
functions such as
(which you already have experience with). For example, in the case of the
function, the input is a list and the output is the number of elements contained in the list.
Methods are functions that can be used with objects. You have already used a number of methods associated with lists (such as
and strings (such as find). We will learn about
the creation of methods when we get to object oriented programming. But, it should be pointed out that the idea of using a method is similar to that of a function in the sense that methods have input values and return output values.
The beauty of a programming language is that, while the language has a finite number of commands, keywords and built-in functions, it is possible to create new user-defined commands using functions and methods. As an example, assume
you have a list of numerical data and you would like to find a value on that list. Assume further that you have a program that must perform this computation at many different points within the program. Under these circumstances it is sensible to write
a function to solve this problem. Let's practice writing a function to find a value on a numerical list.
#begin function definitions ...
#alist is the input list
#x is the value being searched for
#This function returns a bool True if found
#and returns a bool False if not found
for val in alist:
#end function definitions
#main code begins here ...
Copy, paste, and run this code in Repl.it to inspect and study its effect. There are many details to be discussed regarding the syntax of functions.
def informs Python that a function is being declared
Notice the (:) and the indentation with rules similar to conditional statements and loops
Function name: The name of the function is
findval has two input variables,
findval returns one output variable of type bool
The return keyword is responsible for returning the output value
Now that a new user-defined function has been created, the main code that follows can call the function as many times as needed and the function will respond to the specific input variables provided. By default, variables
used within the function are local to the function and cannot be seen by the main commands that follow. The function cannot "see" the variables
b. The main code that calls the function cannot "see" the variables
x within the function. By convention, functions are defined at the beginning of a Python program.
The main code that runs comes after all the functions have been defined.