Writing Functions

This lecture discusses the mechanics of writing functions and how to encapsulate scripts as functions.

Running example

Write a script that determines if a number is prime.

Determine if num is prime


In [12]:
import numpy as np
# Determine if num is prime
# This code has a bug. What is it?
# Also, the efficiency of the code can be improved. How?
num = 8
upper = int(np.sqrt(num)) + 1:
    if num % integer == 0:
        print("Not prime!")
        is_prime = False
        import pdb; pdb.set_trace()
if is_prime:
    print("Is prime!")
is_prime = True
for integer in range(2, upper)


Not prime!
> <ipython-input-12-a2c8341c77b2>(8)<module>()->None
-> for integer in range(2, upper):
(Pdb) help

Documented commands (type help <topic>):
========================================
EOF    c          d        h         list      q        rv       undisplay
a      cl         debug    help      ll        quit     s        unt      
alias  clear      disable  ignore    longlist  r        source   until    
args   commands   display  interact  n         restart  step     up       
b      condition  down     j         next      return   tbreak   w        
break  cont       enable   jump      p         retval   u        whatis   
bt     continue   exit     l         pp        run      unalias  where    

Miscellaneous help topics:
==========================
exec  pdb

(Pdb) exit()
-------------------------------------------------------------------------
BdbQuit                                 Traceback (most recent call last)
<ipython-input-12-a2c8341c77b2> in <module>()
      6 upper = int(np.sqrt(num)) + 1
      7 is_prime = True
----> 8 for integer in range(2, upper):
      9     if num % integer == 0:
     10         print("Not prime!")

<ipython-input-12-a2c8341c77b2> in <module>()
      6 upper = int(np.sqrt(num)) + 1
      7 is_prime = True
----> 8 for integer in range(2, upper):
      9     if num % integer == 0:
     10         print("Not prime!")

~/miniconda3/lib/python3.6/bdb.py in trace_dispatch(self, frame, event, arg)
     46             return # None
     47         if event == 'line':
---> 48             return self.dispatch_line(frame)
     49         if event == 'call':
     50             return self.dispatch_call(frame, arg)

~/miniconda3/lib/python3.6/bdb.py in dispatch_line(self, frame)
     65         if self.stop_here(frame) or self.break_here(frame):
     66             self.user_line(frame)
---> 67             if self.quitting: raise BdbQuit
     68         return self.trace_dispatch
     69 

BdbQuit: 

In [ ]:
# Extending the code to test if a list of numbers is prime
a_list = [3, 6, 11]
# How do we test all elements of the list?

Mechanics of Writing a Function

  • Function definition line - How python knows that this is a function
  • Function body - code that does the computation of the function
  • Formal arguments - arguments passed to the function
  • Return values - value returned to the caller
  • Name scopes

In [15]:
# Transforming the prime number calculation script into a function
def check_prime(num):
    upper = int(np.sqrt(num)) + 1
    for integer in range(2, upper):
        if num % integer == 0:
            return False
    return True

In [19]:
check_prime(-3)


/home/ubuntu/miniconda3/lib/python3.6/site-packages/ipykernel_launcher.py:3: RuntimeWarning: invalid value encountered in sqrt
  This is separate from the ipykernel package so we can avoid doing imports until
-------------------------------------------------------------------------
ValueError                              Traceback (most recent call last)
<ipython-input-19-f39005114c6a> in <module>()
----> 1 check_prime(-3)

<ipython-input-15-24b7803fe8ae> in check_prime(num)
      1 # Transforming the prime number calculation script into a function
      2 def check_prime(num):
----> 3     upper = int(np.sqrt(num)) + 1
      4     for integer in range(2, upper):
      5         if num % integer == 0:

ValueError: cannot convert float NaN to integer

Exercise - Write a Function

  • Write a function that finds two factors of a provided number if it is not prime.
    • What did you name the function?
    • What are the formal arguments? What did you name them?
    • What value(s) are returned?

Crafting a Function

Crafting refers to what you want a function to do.

  • What are the arguments?
  • Should it refer to names outside the function definition?
  • Should it return a value?

Problem: Write a function that finds all of the prime numbers less than a given value.


In [ ]:
# Function header: name, arguments
# Function logic
# return somethin

Exercise - Craft a Function

Create a function (or set of functions) that finds the prime factors of a number.

  • What did you name the function?
  • What are the arguments?
  • What does the function return?