Functions - Python Made Easy (2013)

Python Made Easy (2013)

Chapter 5: Functions

“Programming is not a zero-sum game. Teaching something to a fellow programmer doesn't take it away from you. I'm happy to share what I can, because I'm in it for the love of programming.”- John Carmack

In this chapter you will learn about

· Functions

· Different types of functions

· Arguments

· How to use arguments

Functions are the bread and butter of any large-scale program. All fo the examples that we have worked on through this point have been top-down. This means that the programs begins at the top of the page and executes through the bottom of the page. Functions allow you to create and call on code located elsewhere, throughout the whole of your program. This makes it easy to re-use code several times throughout a program.

What Are Functions?

Functions are pieces of code that can be called to within your program. They are used to break up code and call on certain code as needed. For instance, in most top-down programs, you may need to use the same piece of code several times. This means that when you change the functionality of the program, you mayhave to edit the same block of code several times throughout the program. But, by creating a function– you can then call on that code several times throughout the program.

Later, when you decide to change the functionality of that program, you only have to edit the code once to make changes to multiple code blocks within the program. A function is a block of organized, re-usable code that can be used throughout a program.

All programming languages contain functions in one form or another. Functions are defined in our code using a def statement. This statement is followed by the name of the function, with some parameters outlined in parenthesis.

Defining Functions

Functions must be defined to create and use certain functionality. There are many functions that come built in with the language (such as the print function, for instance), but you can also define your own. When defining functions there are multiple things that need to be noted;

· Function blocks always begin with“def” to define the function.

· All input parameters and arguments must be placed within the parenthesis when you define a function.

· The code block always comes after a colon (:).

· Using the statement“return” will cause you to exit the function.

Here is an example of defining a function;

function_name(parameters)

Defining a function is simple.

Parameters and Returning Functions

When your computer runs a function, it does not see the function name, but rather what the function executed. This means that functions just return the values that they are supposed to, and the names of items defined within the parameters can not be called from elsewhere in the program until they were turned. To make this a bit easier to understand, let's pretend that the function that we have created uses this code;

A = multiply(5)

Now, keep in mind that the multiply function is not a pre-defined function, so this code will not work unless you create it yourself. The program would likely return something like this;

a = 25

This is all that the program would see when you call on the function, and is the only data point that you have available to use throughout the rest of your programs. It ran the function and returned a piece of data based on the parameters that it was given within the code.

Example Function

Now lets check out functions in action so you can visually see how they work within a program. Here is an example function that you can enter into your IDE;

def hello():

print“hello”

return 1234

To call this function, you use this code:

print hello()

When you call the“hello()” function, the program will output the following values;

hello

1234

So what exactly is going on here? A number of things are happening. We are creating a function, calling that function, and observing the output. Keep in mind that in this example, while the program prints both“hello” and“1234,” it actually does not know that“hello” was printed within the function. The program will only be aware of the value that is returned, which in this case is 1234.

Passing Parameters in Functions

Parameters can and often are passed to functions as well. In our example earlier in the chapter, you were given the following line as the basic was to define functions;

function_name(parameters)

We will now go over the usage of parameters when defining functions. The parameters that you place in the parenthesis will be usable by the function itself. Perhaps you have created data that will need to be used within the function? You can pass all sorts of data types to the functions. Here is an example program that allows you to see how defining a function and passing parameters might work in your program.

w = 4

h = 5

Def area(w,h):

return w * h

print area()

This program applies width and height values to the parameters w and h. These parameters are then used in the creation of the function“area.” This function multiples width by height, returning the value. The program calls on this function, and then prints the value returned. The output should be“20”.

Anonymous Functions

Anonymous functions are different in the sense that the keyword, def, is not used to declare them. If you want to create anonymous functions you need to use the keyword, lambda. They can take several arguments at the same time,

These can only return one value but they are incapable of holding more than one expression.

Print cannot be invoked directly, seeing as how one needs to use expressions for anonymous functions. Also, they can only access variables that are within their own parameters or variables that are found in the global namespace. Lambda has its own namespace, too.

The syntax for anonymous functions is as follows:

Lambda [arg1 [,arg2,…..argx]] :expression


Let’s see how this works:

sum = lambda arg1, arg2: arg1 + arg2;

print "Value of total : ", sum( 60, 30 )

print "Value of total : ", sum( 50, 20 )


You will get the following result:

Value of total : 80

Value of total : 70

Lambda is mostly used for small anonymous functions.

As you can see, the return statement is not utilized where lambda functions are concerned. An expression is returned by the function instead.

Variables in Functions

Variables are often used in functions. The same variables may be used several times throughout a Python program. The language has a unique way of dealing with this situations. So far we have only be using global variables. Global variables are accessible throughout the entirety of the program. But, functions have their own special types of variables. These are called local variables.

What this means is that you could have two variables with the same name, for the sake of clarity, lets pretend that we have both a global variable named“a” and a local variable named“a” located inside of a function.

Here is an example that demonstrates how this might work inside of a program;

a = 2

def print_a():

a = 5

print"int print_func a = ", a

print_a()

print"a = ", a,"is a global variable assigned prior to the function print_a"

This then outputs:

Int print_a a = 5

a = 2 is a global variable assigned prior to the function print_a

a = 2 was defined outside of the function, and therefore is a global variable. The local variable that is located inside of the function has the same name, but has been assigned a different value. The local variable inside of the function can only be called within that function, and never outside of it. The global variable can be called anywhere within the program at any time.

Variable assignments inside of a function will never overwrite the global variables that have already been declared. For all intents and purposes– local variables exist only inside of a function.

Function Arguments

Arguments are used to call a function and there are primarily 4 types of functions that one can use: default arguments, required arguments, keyword arguments and variable-length arguments.

Default Arguments


When no value is assigned to the function call, a value is assigned to it so that it is possible to invoke the function. Here’s an example:

def printinfo( name, salary = 3500 ):

"This prints a passed info into this function"

print "Name: ", name;

print "Salary ", salary;

return;

printinfo( salary=4500, name="Jo" );

printinfo( name="Jo" );

The first line defines the default value of the argument. The default value of the argument is used to call the function. The last two lines determine the value that is to be returned by using the default argument. Thus you get the following output:

Name: Jo

Salary: 3500
Name: Jo

Salary: 4500

Required Arguments


As is obvious by the name of these arguments, these are required by the code. You need these to prevent syntax errors and to get the output you want. One argument is required to pass an argument. The program will tell you that a particular function requires you to use at least one argument so it can be passed successfully.

Keyword Arguments


Keyword arguments will invoke the function after the parameters are recognized by their parameter names. The value of the keyword argument is matched with the parameter name and so, one can also put arguments out of order.

def printme( thisstring ):

"This prints a passed string into this function"

print thisstring;

return;

# Now you can call printme function

printme( thisstring = "Our string");

printme() is the function here and once the code is executed you will get the following output:

Our string

Variable-Length Arguments

In some instances you might need to pass more arguments than have already been specified. Going back to the function to redefine it can be a tedious process. Variable-Length arguments can be used instead. These are not specified in the function’s definition and an asterisk (*) is used to define such arguments.
There are non-keyword variable arguments and variable key arguments.

Non-keyword variable arguments are called tuples. These are inserted so that they are made accessible to the program. Here is the syntax for non-keyword variable arguments:

def function_name([formal_args,] *vargs_tuple):

“function_documentation_string”
function_body_suite
return

The asterisk is always placed in front of a variable that is to be used to hold remaining arguments when formal parameters cannot be used anymore. These allow you to hold a variable number of keywords so that any syntax errors can be avoided. Now, let’s see how such arguments work:

def printinfo( arg1, *vartuple ):

"This prints a variable passed arguments"

print "This is the output: "

print arg1

for var in vartuple:

print var

return;

printinfo( 100 );

printinfo( 20,30,40 );

Arg1 holds the remaining variables here. You should get the following output:

This is the output:

100

This is the output:

20

30

40

There are keyword variable arguments too and these are used for extra keywords (or extra sets of these). They are stored in a dictionary and the corresponding value of each keyword is its argument. Two asterisks are used to differentiate keyword variable arguments from non-keyword variable arguments. The syntax for these is:

def function_name([formal_args,] [*vargst,] **vargs_tuple):

function_documentation_string”
function_body_suite
return

This example demonstrates the usage of the double asterisks:

def z(a, b, c, d):

… print (a, b, c, d)




>>> e = {‘a’: ‘apple’, ‘b’: ‘ball’, ‘c’: ‘cold’, ‘d’: ‘dart’

>>> f(**d)

(‘apple’, ‘ball’, ‘cold’, ‘dart’)

You can use single and double asterisks at the same time, too.

PROJECT: Functions

Now you are familiar with functions, so let's test your skills with a project. Try not to look at the answer until you have finished your own program. In this project we will be create a meal planning program. Prompt the user to enter whether they want a low calorie, or high calorie meal. Create functions for both types of meals. If they choose a low calorie meal, print“chef salad with low-fat dressing” and return the value 4.99 (the price). If they choose the high calorie meal, print“cheeseburger with french fries” and return the value 6.99.

Answer:

lowprice = 4.99

highprice = 6.99

def low(lowprice,):

print "Chef salad with low-fat dressing"

return lowprice

def high(high,):

print "Cheeseburger with French Fries"

return highprice

meal = float(input('Enter 1 for a low calorie meal or 2 for a high calorie meal'))

if meal == 1:

print low(lowprice)

else:

print high(high)

Summary

ü In this chapter we learned about:

· Functions

· Arguments

· How to pass parameters in functions

· Arguments

· Different types of arguments- default arguments, variable-length arguments, keyword arguments, non-keyword arguments, required arguments and default arguments

· How to use different types of arguments