Lecture 08 Defining Functions

Joseph Haugh

University of New Mexico

Free Recall

  • Get out a sheet of paper or open a text editor
  • For 2 minutes write down whatever comes to mind about the last class
    • This could be topics you learned
    • Questions you had
    • Connections you made

Start Reading

  • Let’s start by reading chapter 10
  • Take about 10-15 minutes to do this

Defining Functions

  • Up until now you have only been using functions
  • Functions such as abs, len, and range
  • However, now I will show you that you can define your own functions
  • You can do this using the def keyword

Defining a Function

  • Let’s say you want to define a function which sums the numbers from 1 to n and gives you back that sum
  • How would you do this if this was an exercise?
  • Probably something like this:
n = int(input())
result = 0
for x in range(1, n + 1):
    result += x
print(result)

Visualize

Exercise Version: Sum to N

n = int(input())
result = 0
for x in range(1, n + 1):
    result += x
print(result)

Visualize

  • Here you get the input from the outside, from the user of the program
  • You then take that input and do the calculation
  • Finally, you print the result since this is how you return the result to the user
  • Defining functions give you a way to take input from the inside, from the writer of the program

Function Version: Sum to N

def sumToN(n):
    result = 0
    for x in range(1, n + 1):
        result += x
    return result
  • Here we take the input, n, another piece of code
  • We use this input to perform the calculation
  • Then we return the result back
  • How do we actually use this?

Using sumToN

def sumToN(n): # Defining our function
    result = 0
    for x in range(1, n + 1):
        result += x
    return result

print(sumToN(5)) # Calling our function
print(sumToN(sumToN(3)))

Visualize

  • The definition of a function does nothing other than define the function
  • In order to use it we must call it
  • After we call it, it performs its calculations and then returns a value to us
  • We can do whatever we want with this value, such as print it

Defining Functions: Two Parts

  • The first line a function use the def keyword to declare a function name and its arguments
  • The following syntax is required:
    • def <<function name>>(<<argument list>>):
  • If a function needs to return a value to the caller of the function it must use the return keyword
  • The following syntax is required:
    • return <<value>>

Common Mistakes: Forgetting Return

  • It is very easy to forget the return keyword when you meant to use it
  • What happens if you do this?
  • Let’s try it and see:
def add1(n):
    n + 1 # Forgot return!

print(add1(2))

Visualize

It prints “None”, this is the default return if none is specified!

Common Mistakes: Forgetting Return

  • Let’s fix our mistake and try it again:
def add1(n):
    return n + 1

print(add1(2))

Visualize

It works!

Common Mistakes: Indentation

  • The body of a function must be indented past the definition of the function
  • This is the same rule that ifs, loops, and many other statements follow in Python
  • For example:
def add1(n):
return n + 1 # Needs to be indented

print(add1(2))

Visualize

You will get an “Indentation Error”!

Common Mistakes: Indentation

  • Wrong indentation can be more subtle though
  • Consider the following code:
def shout():
    print("Hello!!!???")
print("Are you there!!??") # Should be indented

shout()

Visualize

What will be printed?

Are you there!!??
Hello!!!???

Line 3 needs to be indented!

Common Mistakes: Wrong Number of Arguments

  • Another common mistake is a mismatch in the number of arguments
  • For example:
def add1(n):
    return n + 1

print(add1())     # 0 instead of 1 argument
print(add1(1, 2)) # 2 instead of 1 argument

Visualize

This causes a “Type Error”!

Common Mistakes: Typo

  • The last mistake may be the easiest to make, you simply misspell the name of the function!
  • For example:
def add1(n):
    return n + 1

print(addOne(2))
print(ad1(2))

Visualize

This causes a “Name Error”!

sumNToM

  • What if you also wanted to be able to specify what number to start summing at instead of just specifying the upper limit?
  • Just add another parameter!
def sumNToM(n, m):
    result = 0
    for x in range(n, m + 1):
        result += x
    return result

print(sumNToM(1, 5))
print(sumNToM(10, 25))

Visualize