FUNCTIONS - NTRODUCTION TO PROGRAMMING WITH PYTHON (2015)

INTRODUCTION TO PROGRAMMING WITH PYTHON (2015)

CHAPTER 5. FUNCTIONS

Let’s delve into purposeful programming where the program will demand user input to execute a command or to perform a task.

This is achieved using functions.

Let’s take a real life example say you want to surprise a friend on their birthday. You inform other friends, gather a group, and tell them how the party will go. For example, you decide on a signal at which they will turn on the lights, blow the trumpets, or sing the birthday song. In this scenario, you have created a basic plan of action and a signal (an input) and how everyone (individually) will react to it.

You are not expecting to tell everyone what to do again when you give them the signal, BECAUSE you have already defined different functions and associated signals that will activate them.

In Python, functions are smaller independent pieces of code in your program. They allow you to divide and order your code, and hence make it compact, more organized, and readable. Once created, a function can be used at any time, and any number of times anywhere in your program.

USING A FUNCTION

Python has a library full of pre-made functions for various common tasks. You can use them by simply calling them, and giving them an input.

“Calling” a function simply means using the function name (and not copying the whole code again), and giving the function an input it can compute.

Think of it like calling the movers or the letterman. They know their function, and if you give them the right input (i.e. things to be moved or a letter/parcel), then you would not have to explain it to them what to do with that input. They will complete the job once you give them the right input.

In Python, calling a function is simple. Define a parameter name and its working parameters:

function_name(parameters)

Simple, right?

Let’s understand the details of the syntax shown above:

· Function_Name identifies which function it is you want to use. You will figure it out yourself, as in the previous analogy, if you want to move something you’d call the movers and a letterman if it’s a small parcel/letter. As an example, a basic function is the raw_input function. We’ll use it soon.

· Parameters are the values or the inputs that you pass to the function. This value will inform the function what and how it should use it. For example, if you have a function thatadded a value to a number after multiplying it by 3 then the parameters will be 1) the number it should multiply by 3, and 2) the number it should add to this result. So if you put 5 and 2 in the parameters for this function then it will first multiply (5 x3) and then add 2 (15+2), giving you 17

PARAMETERS AND RETURNED VALUES

Now, functions normally work in the background and will normally not show the result of the computation they have performed on the parameters you have given them.

Returning the value or result of its computation is important to know where the program is, or if it is generating the expected results. What if you have given it a letter or an illegal symbol ($,%, #) instead of a number?

So how does a function show what it does, or has done on the terminal?

Let’s see how the computer sees the function. It does not see the name of the function (or in case of a variable, the variable’s name), rather, it only sees the final value that the function or the variable has stored in it.

Hence, in case of the function, the computer sees the final, end result.

Let’s take the example of a function multiply() that multiplies any number by 7. So, its input is any number you can think of and place it in the brackets, the function multiplies it by 7.

NOTE: multiply() is not a pre-made function in Python. You can’t use it straight out as mentioned here.

So if you typed this:

t = multiply(60)

It will appear to the computer as this:

t = 420

The function ran itself, and returned a number to the main program, using the parameters we had given.

Let’s try a real function, input.

NOTE: Previous versions of Python (<Python 3) used raw_input instead.

The following function asks the user to enter a value that it turns into a string of text. For example:

# the first line makes “t” equal to the value that you type in on the screen

t = input("Type something, and I shall display it on the screen again:")

# The next line will print, or return the value that you have entered in 't'. It will show the result of the function

print (t)

The result is simply the content that you have entered on the screen after the program is run.

NOTE: ‘#’ is used for writing comments in the code. Any line that begins with “#” is not computed by the Python interpreter.

Think of commenting as your in-program documentation, informing or reminding you about what each chunk of code/function does.

It becomes crucial as your code becomes larger and more complex. Practice it from the beginning.

So, if you type in “Really?” in the above program when asked to do so, the computer sees the function as:

t = "Really?"

print ("Really?")

Remember, that to the computer, variable is just a stored value. It does not appear as ‘t’. So is the case with functions. They don’t appear as the whole code, only the value they contain in them.

DEFINING YOUR OWN FUNCTIONS

You can create your own functions using the ‘def’ operator.

Think of a function, and what it will do. Now name it, and use ‘def’ as follows:

def function_name(parameter_1,parameter_2):

#notice the colon ":" at the end of the line? #it is an important part of the syntax. Always #add it at the end of line that starts with #'def'

{this is the code in the function}

{more code}

return {value to return to the main program}

Recall that to the computer, the variable in the function looks like the value that is stored inside it and that functions are similar and only the value that they return is seen by the computer.

It does not matter how large your function’s code is. Only the value matters. Because the function is a separate, self-contained program, it doesn’t see any of the variables in your main program.

Why the stress on what the computer sees?

Here is an example to show the importance. The following function ‘written ()’ will print the word “Functions are independent of the main program” on the screen, followed by returning a number “54321” to the main program.

#creating the function

def written():

print (" Functions are independent of the main program ")

return 54321

# how to use the function

written()

The last line of code is calling the function. When you type that, the function’s values are displayed on the screen and not the complete function:

Functions are independent of the main program

54321

So what happened?

As soon as thedef written() was run, Python created a function and labeled it ‘written’

When the written() was run, Python executed the function ‘written’ that it had previously created. Running the function meant executing all lines of code within in.

The function first printed “Functions are independent of the main program”and then returned the number ‘54321' back to the main program.

As a result, the main program only sees the line as 'print 54321' and so displays '54321’ in the next line. Your function did not know that the string“Functions are independent of the main program”had been printed already, all it saw was that it received a new value ‘54321’ and printed that onscreen.

Functions can also receive arguments i.e. you can pass variables to them. For example:

def a_function_with_args(username, message):

print ("Welcome, %s , I am your new function. I wish you %s"%(username, message))

Functions can also return values.

Functions may return a value to the caller, using the keyword — 'return' as used in the previous example. Another example:

def add_both_numbers(a, b):

return a + b