← All chapters

Python curriculum / Chapter 03

Functions

Creating, calling, combining, and returning values from functions.

Python - 3. Functions

Add the “pass” statement

def myfunction():

pass

3. Functions

3.1 What Is A Function?

3.2 Creating a Function

3.3 Calling a Function

3.4 Function Examples

3.4.1 Multiple Parameters

3.4.2 No return Statement

3.4.3 No Parameters

3.4.4 A More Complex Program

3.4.5 Functions Calling Functions

Chapter 3: Assignments

A3.1 - Say Hello

A3.2 - Square a Number

A3.3 - Basic Math With Two Numbers

A3.4 - Using One Method a Few Times

Key Terms

3. Functions

3.1 What Is A Function?

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

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

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.

  1. 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.
  2. 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)
  3. 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

3.4.2 No return Statement

def example_2(a, b):

print (a * b)

example_2(3,10)

OUTPUT TO THE SCREEN:

30

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?

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

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.

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!

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:

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:

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:

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.