Lesson 5: Writing Modular Code

1. Functions

1) What is a function?

A function is a block of reusable code intended to perform similar operations multiple times. We saw some built-in functions in Python II, including round(), raw_input() and length(). Python has these functions by default, because the makers of python know that many users will want to do things like rounding a number.

However, you can also create your own functions, tailored for what you need your code to do!

2) Why create & use functions?

  • Allows you to re-use a certain piece of code in a different context without re-writing it.
  • Organizes your code into functional pieces.
  • Makes code easier to read and understand.

3) How do you create a function?

The syntax is very simple. The first line has the string 'def', followed by whatever you want to call your function, followed by whatever you want to call your inputs, in parenthesis.

Functions usually do something with the parameters they are given, and then return the result using a 'return' command. An example of this is the int function, which takes in a string, and returns that string converted to an integer.

For instance, if I want a function that returns the highest of two numbers squared, the code would look like:


In [0]:
def squareMax(num1, num2):
    maxNum = max(num1, num2)
    return maxNum*maxNum

Functions don't always require input. In the following example, the function outputs a string which we can store to a variable. Try running the following code:


In [0]:
def noInput():
    answer = "abcd"
    return answer

output = noInput()
print output
print answer

Why are we able to print the "output" variable, but not the "answer" variable? When a variable is defined within a function, it is not stored outside the function. Only the values passed through return() are accessible outside the function.

4) How do you call a function?

I can then call this function with the syntax: squareMax(num1, num2). Now run the following functions, so that the result is printed below.


In [0]:
print squareMax(5,2)

In [0]:


In [0]:
print squareMax(3,3)

In [0]:

5) How do you use a function within a larger python project?

Functions are often used within a larger python script. For instance, I may want to square the maximum of two numbers obtained from some other python operation. To do this, the function must be defined first, followed by the rest of the code.

For example, in the following code, the length of two lists is calculated, and then squareMax is used to find the square of the larger of those two lengths. Even though the function squareMax is defined first, the computer starts running the code on the first line of code that is not part of the function. So in this case, it starts at the line where the list a is initialized.


In [0]:
def squareMax(num1, num2):
    maxNum = max(num1, num2)
    return maxNum*maxNum

a = ["blue","red"]
b = ["green","purple","blue","yellow"]
aSize = len(a)
bSize  = len(b)
print squareMax(aSize,bSize)

6) Test your understanding.


In [0]:
import random

#Removes a random letter from the given word
def removeLetter(word):
    wSize = len(word)
    posToRemove = random.randint(0,wSize-1) #choose which character to remove
    return word[:posToRemove] + word[(posToRemove+1):] #adds the string before that character to the string after
    
print removeLetter("abc")

1) What possible strings could be returned by this function?


In [0]:

2) What could go wrong with the removeLetter function if it is used in another context? (Hint: think about which lengths of strings it could be passed, and try to think of a valid string that would cause an error)


In [0]: