Python - 3. Functions
Add the “pass” statement
- function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.
def myfunction():
pass
3.4.5 Functions Calling Functions
A3.3 - Basic Math With Two Numbers
A3.4 - Using One Method a Few Times
3. Functions
3.1 What Is A Function?
- You have been studying functions in math for years. The basic concept is that there is an input, something is done with that input, and the result is the output. In general, a function can be represented like this:
- Here is an example:
This example defines a rule. Whatever value you hand the function is multiplied by 2 and then three is added to it. The input is X and the output is Y. For an input of 10, the output is 23. For an input of -6, the output is -9. Mathematically, this is usually written as:
f(X) = 2X + 3
In Python, the function would be written like this:
def first_function(x):
return 2*x+3 # this is indented beyond the first line
3.2 Creating a Function
- Let’s examine the function example from the previous section:
def first_function(x):
return 2*x+3
def - Tells Python that you are defining a function
first_function - The name (identifier) of the function that you create
(x) - The input for the function is held in parenthesis. These values are known as parameters and can be named whatever you want. There can be zero, one or multiple parameters. You can add as many arguments as you want, just separate them with a comma.
“ : ” - The colon is used to signal the beginning of a function definition block. Everything after the colon that is indented is considered to be part of the function. Anything written after it that is not indented signals the end of the block. This is a common way to order things in Python and you will see it a lot.
return - This is a keyword that tells the computer to exit the function and return the value that follows it to where the function was called (more on that later). A return statement with no arguments after it will just exit the function and return nothing back to the caller (place where the function was called).
3.3 Calling a Function
- A function sitting alone doesn’t do anything. This is how we would use the function we have been discussing. Here is a full program:
def first_function(x):
return 2*x+3
print( first_function(7) )
OUTPUT TO THE SCREEN:
17
In this program, the first_function is defined in the first two lines including a heading and its return statement. The print statement, which isn’t indented, is where the program actually starts.
- The steps that the computer takes when reading this program:
- Start at the top. Here is a definition of a function called first_function. Everything below the heading that is indented is part of that function. I will continue reading beyond that function.
- There is a print statement. What is to be printed? Whatever is inside the parentheses. That happens to be the result of whatever the first_function function gives me back when I hand it the value of 7. (purple part above)
- first_function has already been defined at the top. The function is executed with an argument of 7 which becomes the value of the parameter (x in this case) and the return value is 17 (2 times 7 plus 3). It is returned to the print statement. The entire purple portion of the print statement is replaced by 17 and printed to the screen.
3.4 Function Examples
We have been using a function since chapter 1. The print command that we have been using is actually a function. If we look at it simply, print(“hello”) is a function with the string hello as a parameter. The parameter is printed to output. The print function gets more complex, but the fundamentals of functions can be seen with this example.
3.4.1 Multiple Parameters
def example_1(a, b):
return a * b # Don’t forget about the indentation. It is
usually two spaces
print(example_1(4,5))
OUTPUT TO THE SCREEN:
20
- In this program, we have created a function that takes two parameters, multiplies them together, and returns that value. When that function is called in a print statement, the result is printed.
3.4.2 No return Statement
def example_2(a, b):
print (a * b)
example_2(3,10)
OUTPUT TO THE SCREEN:
30
- This program does the same thing as the example in 3.3.1 but it is structured differently. Here, the function is defined with two parameters, but this time it is missing a return statement. The function is called and handed the parameters 3 and 10. The function prints the result of the product directly to the screen and doesn’t return anything back to the place from where it was called.
- This is a confusing point for people new to programming. The important thing to remember here is that:
- a return statement returns things back to the program where the function was called,
- while output is sent information that cannot be used by the program and is only meant to be displayed or collected. Output is usually sent to the screen but can also be directed to a file.
As a programmer, how the program is working and what information the program has to work with is where your mind is at. When you run the program, you have to switch perspectives and change to how the user of the program is experiencing the running of the program. This is subtle but important.
3.4.3 No Parameters
def greeting():
return "It is very nice to meet you!! May I take your coat?"
print(greeting())
OUTPUT TO THE SCREEN:
It is very nice to meet you!! May I take your coat?
- This is a simple example of a program that generates a greeting. It could be useful if we wanted to call a longer greeting multiple times throughout a program. Notice that we are not handing the function any parameters. This works, but we have to remember to still use the parenthesis, even though they will be empty.
3.4.4 A More Complex Program
def name_combine(first, last):
return first + " " + last
def sentence_generator(x):
print("Nice to meet you " + x)
a = "Alec"
b = "Ying"
c = name_combine(a,b)
print("Your name is " + c)
sentence_generator(c)
OUTPUT TO THE SCREEN:
Your name is Alec Ying
Nice to meet you Alec Ying
- Program breakdown:
- There are two functions defined at the top:
name_combine - Takes in two parameters and returns a string which is a combination of the two parameters with a space between them.
sentence_generator - Takes in one parameter and prints Nice to meet you with the parameter at the end of the string.
- Three variables are then defined. a and b are strings and c becomes whatever value is returned when the name_combine function is called.
- There is a print statement that prints out Your name is along with the value of c.
- The final line calls the sentence_generator and gives the value of c as a parameter. That function prints Nice to meet you along with the value of c.
- Program layout: As our programs begin to get a little bigger, let’s look at the layout. Here is the same program as above, but the blank lines have been removed. This will not affect the program. The lines are there so that the program is easier for humans to read.
def name_combine(first, last):
return first + " " + last
def sentence_generator(x):
print("Nice to meet you " + x)
a = "Alec"
b = "Ying"
c = name_combine(a,b)
print("Your name is " + c)
sentence_generator(c)
The important spacing to keep in mind is the indentation of the contents of the functions. This defines blocks and will be used all the time.
3.4.5 Functions Calling Functions
def func1():
print("hello from func1!")
def func2():
func1()
func1()
func2()
OUTPUT TO THE SCREEN:
hello from func1!
hello from func1!
- Following the flow of this program starts at the top and reads down:
- func1 is defined.
- func2 is defined.
- The last line of the program is func2(). This is where the program begins to execute by calling the function. There are no parameters to deal with.
- func2 begins by calling func1, which prints hello from func1!
- func2 continues by calling func1 again, which prints hello from func1!
Chapter 3: Assignments
A3.1 - Say Hello
Create a function called hello that has a parameter called name. When the function is called, it should print a message to the screen, as shown in the example below. Call the function using an argument with a value of “Sally”.
PROGRAM STRUCTURE:
########################################
## Program title, author, date and description
########################################
# define the function (don’t forget the colon at the end) like this:
def hello(name):
# indent the body of the function that prints to the screen
# leave a blank line once the function body is complete
# call the function using “Sally” as the argument
OUTPUT:
Hello there Sally!
A3.2 - Square a Number
Overview: In this assignment, you will ask the user of the program to enter a number and will then return the square of that number.
Details:
- Create a function called square that takes one number as a parameter which can include decimal numbers. The function will find the square of this number by multiplying it by itself. Use a return statement to send that value back to where the function was called in the program.
- Ask the user for a number, which can include a decimal.
- You will send that value to the function.
- The program should then print the result as shown in the example.
PROGRAM STRUCTURE:
########################################
## Program title, author, date and description
########################################
# define the function (don’t forget the colon at the end)
# indent the body of the function that prints to the screen
# leave a blank line once the function body is complete
# Ask the user for a number as input
# Send that number to the function and print out the result
SAMPLE RUN #1:
Please enter a number. It can also be a decimal: 4
4 squared is 16.
SAMPLE RUN #2:
Please enter a number. It can also be a decimal: 3.4
3.4 squared is 11.56.
A3.3 - Basic Math With Two Numbers
Overview: Take in two numbers and add, multiply, and subtract them with each operation being done in a separate function.
Details:
- Create three separate functions called add, mult and sub that take in two parameters and each perform their operation. None of them should have a return statement and should print the answer directly to output.
- Ask the user for two integers.
- Call all three functions.
PROGRAM STRUCTURE:
########################################
## Program title, author, date and description
########################################
# Create the add function
# Create the mult function
# Create the sub function
# Ask the user for two numbers as input
# Call the three functions
SAMPLE RUN:
Please give me a number to do some math on: 7
Please give me a second number: 2
Thanks!
7 + 2 = 9
7 * 2 = 14
7 - 2 = 5
A3.4 - Using One Method a Few Times
Overview: Find the average of a first batch of numbers, a second batch of numbers and then the average of those two batches. The program will use the average function three separate times.
Details:
- Create a function called avg that takes two parameters and returns the average.
- Create four variables that each hold a number
- Call the function to average the first two numbers
- Call the function to average the second two numbers
- Call the function to average the first two averages
- Print out the overall average
PROGRAM STRUCTURE:
########################################
## Program title, author, date and description
########################################
# Create the avg function
# Define four variables. Use the following four hard coded numbers:
first_batch1 = 6
first_batch2 = 12
second_batch1 = 10
second_batch2 = 30
# Using the avg function, find the average of the first two numbers and store that in the
# variable first_batch_avg
#
# Using the avg function again, find the average of the third and fourth numbers and
# store that in the variable second_batch_avg
#
# Call the avg function a third time to find the average of first_batch_avg and
# second_batch_avg.
#
# Print the overall average to the screen.
OUTPUT:
The overall average is: 14.5
Key Terms
function - A named section of a program that performs a specific task.
parameter - A special kind of variable used in a function to represent one of the pieces of data provided as input to the function.
argument - The pieces of data with which the function is going to be called/invoked.