First, Let's Make Sure We're Speaking the Same Language!
A Function (Again)
What's a function? →
a function…
is a named sequence of statements that performs some useful operation
may or may not take parameters (produce a value)
may or may not produce a result (return a value)
Examples
What are some examples of built-in functions or functions in modules? →
built-in functions
print("something")
int("5")
intput("enter a number)
functions in modules
math.sqrt(5)
sys.exit()
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 →:
the function name
followed by parentheses
with zero or more arguments enclosed within those parentheses
(no arguments are ok)
Arguments
Based on the definitions of function and calling a function, how can we define argument? →
an argument is a value provided to a function when the function is called
this value (or values) is used within the function
the argument can be the result of an expression which may involve operators, operands and calls to other functions!
or simply, the input
Arguments / Parameters
What's the difference between an argument and a parameter?
argument: value provided to a function when it's called
parameter: name used inside a function to refer to the value which was passed to it as an argument
we'll see more about this when we create our own functions!
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? →
randint(1, 10)
input("Enter a number")
float(23)
int
str
float
We Can Define Our Own Functions!
What's the name of this function? How many arguments do you think it takes? What does the function do?
create_greeting
one argument
returns a string
Defining a Function - Syntax
Based on our examples, let's figure out how we define a function:
The Function Header
the keyword, def (this never changes)
followed by the function's name
(whatever you want, but something meaningful)
same rules for variable names apply (alphanumeric and underscores)
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
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".
sometimes we'll use parameter and argument interchangeably
note that whatever value you pass in to the function, you can now refer to it within the body using the parameter's name
we'll take a look at this in a little bit…
Function Body
The body of a function:
consists of one or more statements
the values that were passed in as arguments in the call to the function:
can be accessed by the parameter names
these names correspond to the position that they were in when the function was called
an optional return statement that specifies to the function that it should give back a value
(most of the functions we write will have a return statement)
…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).
Parameters Example 1:
Using the following function and function call, what are the values of both greeting and num within the function? →
greeting → "hola"
num → 23
Parameters Example 2:
Using the following function and function call, what are the values of both greeting and num within the function? →
greeting → "hey there"
num → 5
Parameters Example 3:
Using the following function and function call, what are the values of both greeting and num within the function? →
greeting → "hi"
num → 20
Let's Take a Closer Look
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:
defining a function doesn't call a function
you must explicitly call it after it is defined…
(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? →
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? →
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? →
Program Flow
What we've seen so far:
statements are executed from top to bottom
each line is executed exactly once
Program Flow Coninued
Defining our own functions means:
still top to bottom, so we have to define the function first
but once a function is called…
go to function
execute that code
go back to where function was called
the body of a function can be executed as many times a function is called
Program Flow Example
Let's walk through this program line-by-line →
Using a Main Function
Sometimes you'll see a function called main() within a program
this signifies that this is the main line of execution
all of the code for the program is written in that function
the last line of the code calls that function
the rationale for doing this is to:
keep your code organized
isolate your function definitions from the actual program (handy when creating modules)
we'll see this a bit more later…
Returning Values
we can create fruitful functions, that is… functions that return a value
define a function using def, and just use the keyword return, followed by the value that you want to give back
(you might have noticed the keyword, return in previous examples)
Without Return (None)
In this example, we do not have a return statement. This is still syntactically valid, but…
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.
The return Statement
the return immediately stops the execution of a function
…and returns the value that follows it
the value can be any value!
it can even be an expression
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? →
string, "foo"
string, "bar"
string, "10!"
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.→
Area, Defined Again
Another way to define our area function:
code is shorter
but no intermediary variable (maybe more difficult to debug?)
Print vs Return
What's the difference between printing in a function and returning a value from a function? →
Print vs Return Continued
What's the difference between printing in a function and returning a value from a function?
printing alone will not give you back a value for a function!
however, you can print and return
useful for debugging
see the example below… where we print out what s is before returning it
Stopping Execution
The return statement stops execution of your function immediately. What gets printed in the following example? →
"one" and "two" are printed, but three is not because the function has already returned the value "foo"
Another Example…
Stopping execution again…
Multiple Return Statements
You can have multiple return statements in your function! Write a function that calculates absolute value. →
Some Exercises
create a function that returns the largest factor of a number that isn't the number itself
create two funcions: is_even and is_odd…
each will take one argument (an int)
it will use modulo to determine if the number is even or odd
it will return True or False
(arguably easier to understand than just modulo alone)