Creating Functions

First, Let's Make Sure We're Speaking the Same Language!

A Function (Again)

What's a function? →

Examples

What are some examples of built-in functions or functions in modules? →

Calling a Function

Define what it means to "call" a function. How do we call a function? →

A function call is the statement that actually executes a function. It causes the functions code to run.

Syntactically, we call a function by writing →:

  1. the function name
  2. followed by parentheses
  3. with zero or more arguments enclosed within those parentheses
  4. (no arguments are ok)

Arguments

Based on the definitions of function and calling a function, how can we define argument? →

Arguments / Parameters

What's the difference between an argument and a parameter?

Functions That Return Values

We've used some functions that return values, and we looked at them in an earlier set of slides. What type of values do the following functions give back? →

We Can Define Our Own Functions!

def create_greeting(person):
	return 'hello ' + person

What's the name of this function? How many arguments do you think it takes? What does the function do?

Defining a Function - Syntax

Based on our examples, let's figure out how we define a function:

def <function_name>(<zero_or_more_parameters>):
	<statement #1>
	<statement #2>
	.
	.
	<etc.>
	# optional
	return some_value

The Function Header

  1. the keyword, def (this never changes)
  2. followed by the function's name
    • (whatever you want, but something meaningful)
    • same rules for variable names apply (alphanumeric and underscores)
  3. parentheses surrounding parameters (if any)
    • can just be () if no parameters are required
    • multiple parameters are separated by commas
    • the parameters specify what information must be provided to the function
  4. a colon to signify the end of the header line

Parameters

A parameter is "a name used inside a function to refer to the value which was passed to it as an argument".

Function Body

The body of a function:

…And Back to Parameters

Let's see what that means. Whatever values you pass in to the function, you can now refer to it within the body using the parameter's name (based on the position of the argument).

def greet_more_input(greeting, num):
	s = greeting * num
	return s

greet_more_input("hello", 5)

Parameters Example 1:

Using the following function and function call, what are the values of both greeting and num within the function? →

def greet_more_input(greeting, num):
	s = greeting * num
	return s

greet_more_input("hola", 23)

Parameters Example 2:

Using the following function and function call, what are the values of both greeting and num within the function? →

def greet_more_input(greeting, num):
	s = greeting * num
	return s

print(greet_more_input("hey " + "there", math.sqrt(25)))

Parameters Example 3:

Using the following function and function call, what are the values of both greeting and num within the function? →

def greet_more_input(greeting, num):
	s = greeting * num
	return s

num = "hi"
greeting = 20
greet_more_input(num, greeting)

Let's Take a Closer Look

#                     num       greeting
#                       |        |
#                     "hi"      20
#                       |        |
def greet_more_input(greeting, num):
	s = greeting * num
	return s

num = "hi"
greeting = 20
print(greet_more_input(num, greeting))

Function Definition

The entire block of code you wrote, the header and the body of the function, is called the function definition. Here are a few things to note about your function definition:

  1. defining a function doesn't call a function
  2. you must explicitly call it after it is defined…
  3. (and related…) a function must be defined before it's called!
    • if you call it before you define it, you get an error
    • specifcally a NameError
    • (similar to what happens when using an undeclared variable)

Function Definition Example 1:

If this is the only code in your program, and you run it, what will be printed to the screen? Something, nothing, or an error? →

def greet():
	return 'hello'

print(greet())
hello

Function Definition Example 2:

If this is the only code in your program, and you run it, what will be printed to the screen? Something, nothing, or an error? →

def greet():
	return 'hello'
#  nothing (the function was never called after it was defined)

Function Definition Example 3:

If this is the only code in your program, and you run it, what will be printed to the screen? Something, nothing, or an error? →

print(greet())

def greet():
	return 'hello'
#  we called the function before defining it
NameError: name 'greet' is not defined 

Program Flow

What we've seen so far:

Program Flow Coninued

Defining our own functions means:

Program Flow Example

Let's walk through this program line-by-line →

def exclaim(word, num):
	punctuation = num * '!'
	s = word + punctuation
	return s

print("hello")
print(exclaim("hi", 1))
print("hey there")
print(exclaim("howdy", 10))

Using a Main Function

Sometimes you'll see a function called main() within a program

Returning Values

def greet(greeting, num):
	s = greeting * num
	return s

Without Return (None)

In this example, we do not have a return statement. This is still syntactically valid, but…

def greet(greeting, num):
	s = greeting * num

print(greet('hello', 5)

If you omit return, you'll get a special value back: None. This prints out None to the screen!

None is a value that means the absence of a value!

So, Now What?

Now that you have a function that returns a value, you can use that function wherever you would use that value.

def greet(greeting, num):
	s = greeting * num
	return s

#  using the return value of greet as an argument to input!
response = input(greet("hi", 3))
print(response)

The return Statement

Some Examples of the Return Statement

These functions are contrived examples of what you can do with return. What type and value do they return? →

def foo():
	return "foo"

def bar():
	return "b" + "ar"

def baz():
	return str(math.sqrt(100)) + "!"

Let's Try Creating a Function That Returns a Value

Write a function that returns the area of a circle (πr²)when given a radius, r.→

import math
def area(r):
	a = math.pi * r * r
	return a

Area, Defined Again

Another way to define our area function:

import math
def area(r):
	return  math.pi * r * r

What's the difference between printing in a function and returning a value from a function? →

def greet(greeting, num):
	s = greeting * num
	print(s)

def greet(greeting, num):
	s = greeting * num
	return s

What's the difference between printing in a function and returning a value from a function?

def greet(greeting, num):
	s = greeting * num
	print(s)
	return s

Stopping Execution

The return statement stops execution of your function immediately. What gets printed in the following example? →

def foo():
	print("one")
	print("two")
	return "foo"
	print("three")

foo()

"one" and "two" are printed, but three is not because the function has already returned the value "foo"

Another Example…

Stopping execution again…

>>> def area(r):
...   a = math.pi * r * r
...   print("before return")
...   return a
...   print("after return")
... 
>>> area(6)
before return
113.09733552923255

Multiple Return Statements

You can have multiple return statements in your function! Write a function that calculates absolute value. →

def absolute_value(x):
	if x >= 0:
		return x
	else:
		return x * -1

Some Exercises