In this module you will explore how to write your own custom functions in Python. Functions are often used as a technique to break up complicated problems into simple, reusable blocks of code.
A function is an organized collection of statements within a program that can be called upon to perform a specific action. Since the beginning of the semester, we have been using a number of Python’s built-in functions, including the
As you continue to write programs, they will inevitably become more and more complex. In order to help organize and make sense of such a large amount of code, programmers often organize their programs into smaller, more manageable chunks by writing their own functions. This lets us break down a program into several small functions, allowing us to focus on one isolated portion of a program at a time. Some benefits to using functions include:
get_sales_figures() compute_tax() generate_output()
Defining your own functions is easy in Python. To begin, you need to make up a name for your function. Functions follow the same naming rules that exist for variables (no spaces, can't start with a number, etc - see Module 1 for a full discussion on valid names for variables)
Defining functions requires the
def keyword followed by the name of the function you wish to define. Next, you need to add two parenthesis after the name of the function and the "colon" character. From there you can indent any number of lines of code within your newly created function. Here’s an example function definition:
# this defines a function called "myfunction" def myfunction(): print ("Printed from inside a function")
Defining a function doesn't run the code inside of the function - it simply tells Python that you have created a function with a particular name. To actually use your function you need to call it, much like how you have to call a pre-written function like the
def myfunction(): print ("Hello, world!") ##### main program ##### # call the function that we just wrote myfunction()
As you can see, functions must be defined before they can be used. The following code wouldn't work in Python because the function "myfunction" doesn't exist yet when it is called:
myfunction() def myfunction(): print ("Hello, world!")
In Python we generally place all of our functions at the beginning of our programs or in an external module.
Once a function has completed, Python will return back to the line directly after the initial function call. For example:
Sample Program: This program illustrates the flow of a program with multiple function calls:
When a function is called programmers commonly say that the “control” of the program has been transferred to the function. The function is responsible for the program's execution until it runs out of statements, at which time control is transferred back to the point in the program that initially "called" the function.
Sample Program: This program defines two functions - "top"and "side" - which are used to draw a rectangular shape using the asterix character.
Programming Challenge: Write a program that generates the following pattern. Use functions to break up the problem into reusable blocks of code. Refer to the previous programming challenge as necessary! Click the "Run" button to check your work, and click here to download the solution.
##### # # # # # # # # # #####
You can define variables inside functions just as you would in your main program. However, variables that are defined inside of a function are considered local to that function, which means that they only exist within that function and are no longer available once the function has completed executing. We refer to these variables as local variables.
Code that is written outside of a function will not be able to access a local variable created inside of a function. Here’s an example of how this works - the code below will result in an error because the main program is trying to access a local variable that was defined inside of a function:
# define a function that asks the user to enter a # number of items they wish to purchase def purchase(): numitems = int(input("How many items do you want to buy? ")) print (numitems) # call the purchase function purchase() print (numitems) # error! Variable numitems doesn’t exist in this scope!
Different functions can have their own local variables that use the same name. Even though the variables share the same name, they are considered completely different variables that have no relationship to one another.
def square(): num = 2 print ("Square of", num, "is", num**2) def cube(): num = 3 print ("Cube of", num, "is", num**3) square() cube()
Sometimes it is useful to not only call a function but also send it one or more pieces of data as "arguments." For example, when you call the print function you can send it an argument, like this:
We can do the same thing with our own functions, like this:
When passing arguments, you need to let your function know what kind of data it should expect to receive. You can do this by establishing a variable name in the function definition - these variable names go inside of the set of parenthesis after the function name.
# function that accepts one argument - a def my_function(a):
Argument variables are automatically declared every time you call your function, and will assume the value of the argument passed to the function. Here's an example function that accepts a value and stores it in the local variable "num":
Sample Program: This program demonstrates how you can call a function that is designed to accept an argument.
You can actually pass any number of arguments to a function. One way to do this is to pass in arguments "by position." Here’s an example:
# the average function expects 3 arguments
def average(num1, num2, num3): sum = num1+num2+num3 avg = sum / 3 print (avg) # call the function with 3 arguments average(100,90,92)
In the above example, the function argument variables (num1, num2 and num3) assume the values of the arguments passed into the function (100, 90, and 92)
When we pass an argument to a function in Python we are actually passing its "value" into the function, and not an actual variable. We call this behavior "passing by value." We are essentially creating two copies of the data that is being passed – one that stays in the main program and one that is passed as an argument into our function. This behavior allows us to set up a "one way" communication mechanism – we can send data into a function as an argument, but the function cannot communicate back by updating or changing the argument variable because it is "local" to the function.
Sample Program: This program demonstrates how arguments allow you to "pass by value" - the argument variable is merely a "copy" of the data being sent into the function.
When you create a variable inside a function we say that the variable is "local" to that function. This means that it can only be accessed by statements inside the function that created it. When a variable is created outside all of your functions it is considered a "global variable" — global variables can be accessed by any statement in your program, including by statements in any function. All of the variables we have been creating so far in class up until this module have been global variables.
Sample Program: This program demonstrates how a global variable can be viewed from within a function
However, if you want to be able to change a global variable inside of a function you must first tell Python that you wish to do this using the
global keyword inside your function. If you don’t use this keyword, Python will assume that you want to create a new local variable with the same variable name as the global variable. Technically this isn’t an error, but it can get confusing!
Sample Program: This program demonstrates how a global variable can be viewed and changed from within a function
Programming Challenge: Write a function that converts a number from feet to inches (12 inches in a foot) and another function that converts feet to meters (0.3048 meters in a foot). Each function should accept a single argument and use that argument to calculate the conversion and print the result. Next, write a program that generates the following output - make sure to use your functions in your program! Click the "Run" button to check your work, and click here to download the solution.
0 ft: ... 0 inches ... 0 meters 1 ft: ... 12 inches ... 0.3048 meters 2 ft: ... 24 inches ... 0.6096 meters 3 ft: ... 36 inches ... 0.9144 meters 4 ft: ... 48 inches ... 1.2192 meters 5 ft: ... 60 inches ... 1.524 meters 6 ft: ... 72 inches ... 1.8288 meters 7 ft: ... 84 inches ... 2.1336 meters 8 ft: ... 96 inches ... 2.4384 meters 9 ft: ... 108 inches ... 2.7432 meters
"Value returning functions" are functions that have the ability to send back, or return, information to the part of your program that called them. We've been using value returning functions since the beginning of the semester. For example, the "input" function is a value returning function - it "returns" a string when it is finished executing. We often capture that string and store it in a variable for later use in our program.
name = input("What is your name? ")
Syntactically value returning functions are almost identical to the types of functions we have been writing so far. The only difference is that you need to include a
return statement in your function to tell Python that you intend to send back a value to whatever part of your program called the function. Here’s an example function that returns an integer to the caller:
def myfunction(): x = 5 return x somenumber = myfunction() print (somenumber)
When a function reaches a return statement it immediately ends the function and sends back the value attached to the statement. For example, this function will end early if you send it an even number as an argument because the return statement is reached prior to the second print statement:
Sample Program: The
return statement will immediately cause a function to end and send back whatever value is attached to the return statement.
Note that in the above example we are storing the return value in a variable. This is functionally identical to when we store the string result that gets returned from the
input function or the integer result that gets returned from the
Sample Program: This program contains two functions - one function is used to ask the user for a price value and another function is used to apply a discount to a price value. Both functions are then used as part of a larger program.
In Python, functions can return more than one value. You can do this by separating the return values using a comma. Remember that if you return more than one value then your calling program must be expecting the same number of values. Here’s an example:
Sample Program: This program shows how a function can return multiple values in Python. Note that if you return multiple values from a function you also need to capture those values when calling the function. You can do this by separating the variables used to capture the return values using commas.
Programming Challenge: Write a function that rolls two dice. Your function should be designed to accept a single argument (an integer) and generate two die rolls between 1 and the number supplied. Your function should then return the two rolls in ascending order. Next, write a program that rolls 5 sets of dice with different sides. Here's a sample running of your program:
6 sided dice roll: 2 & 4 7 sided dice roll: 3 & 4 8 sided dice roll: 1 & 8 9 sided dice roll: 7 & 7 10 sided dice roll: 4 & 6
Click the "Run" button to check your work, and click here to download the solution.
Now that you've completed this module, please visit our NYU Classes site and take the corresponding quiz for this module. These quizzes are worth 5% of your total grade and are a great way to test your Python skills! You may also use the following scratch space to test out any code you want.