Functions

A function is a set of statements that you store and can run multiple times. We have already used some functions.

type("I've been using functions since the beginning?")

This is a built in function called 'type'. A function takes arguments (values you put between the parentheses) and returns a result. In this case it takes the arguments of "I've been using functions since the beginning?" and returns the result of "str".

Built in Functions

There are lots of predefined functions in python. Here are some of them

len(list) -> returns the number of items in a list
max(list) -> returns you the maximum value of the list (strings are lists)
min(list) -> returns minimum value of list

In [ ]:
my_string = "Howdy, welcome to my ranch?"

print(len(my_string))
print(max(my_string))
print(min(my_string))

TRY IT

Create a string with your name and store in a variable called name

Then find and print the length and max letter of name.


In [ ]:

Type Conversion Functions

Some of the built in functions are to convert values of one type into another.

int(value) -> converts to int
float(value) -> converts to float
str(value) -> converts to string
bool(value) -> converts to boolean

If the value can't be converted, the function will throw an error


In [ ]:
# Integer
int('5')

In [ ]:
# float
float(5)

In [ ]:
# string
str(5)

In [ ]:
#boolean
bool(1)

In [ ]:
# Uh-Oh - python doesn't do number words
int('five')

TRY IT

Convert the string '3.6' to a float


In [ ]:

Modules and Random numbers

Python includes functions to generate pseudorandom numbers. This comes in handy a surprising frequently amount of times. (What is the difference between pseudorandom numbers and random numbers? If given the same seed, pseudo random numbers will come up with the same series every time.)

You will need to import a module to use random numbers. A module is a collection of functions, objects, and values that you can use if you bring it into your program using an import statement. Then you can access these using 'dot notation'.

import module
module.function()
module.value

The random module has a function called 'random()' that returns a random float from (0, 1]. That means including 0 but excluding 1.


In [ ]:
import random

#Your value should be different from mine.
random.random()

You can get help on modules that you import by typing a question mark after the module. (This only works in an ipython notebook, not from the command line)


In [ ]:
random?

You can also get help on functions within the modules


In [ ]:
random.randint?

There is also a function to generate a random integer.

randint(low, high) generates a random number between low and high (including both).


In [ ]:
random.randint(0,6)

TRY IT

Get a random value from 1-20.


In [ ]:

Math Module

The math module has more advanced math functions and constants than the arithmetic operators.

Here is the full API: https://docs.python.org/2/library/math.html

Constants:

pi

e

Sample of functions:

sin(x) - sine of x (radians)

cos(x) - cosine of x (radians)

tan(x) - tangent of x (radians)

log(x) - logarithm of x (base e)

floor(x) - rounds floating point number down to nearest int.


In [ ]:
import math

# using constant
radius_of_pig_pen = 5
circumference = math.pi * 2 * radius_of_pig_pen
print(circumference)

# using functions
print(math.sin(0))
print(math.cos(0))

TRY IT

Find the floor of 4.6732


In [ ]:

Adding your own functions

You can define your own functions using the def keyword. Defining a function does not run the lines of code within the function.

def function_name():
   line 1
   line 2

Once you have defined a function, you can call it and run the code within the function.

function_name()

In [ ]:
def yeehaw():
    print("YEEHAW")
    
#notice that nothing is printed, the functions is not run unless you call it

In [ ]:
# lets call our new function
yeehaw()

You can call your function within another function


In [ ]:
def cowgirl():
    yeehaw()
    print("I'm gonna lasso me some cattle")
    yeehaw()
    
# Got to run it
cowgirl()

TRY IT

Write a function called ranch() that prints out your favorite farm animal and the noise it makes. Call your function.


In [ ]:

Parameters and arguments

You can have your function take one or more variables as input, these are called arguments. Arguments are assigned to parameters (named variables). You can use the parameters inside the body of the function

def myfunc(parameter1, parameter2):
    print(parameter1)

myfunc('hello', 'goodbye')


Giving the function different arguments can change the way it behaves.


In [ ]:
def feed_animal(type_of_feed):
    if type_of_feed == 'oats':
        print("Feeding the horse")
    elif type_of_feed == 'hay':
        print("Feeding the cows")
    else:
        # pigs eat anything
        print("Feeding the pigs")
        
feed_animal('hay')

feed_animal('apple')

TRY IT

Create a function called pet that takes a parameter called animal. The function should print out 'Petting the ' + animal


In [ ]:

Return

Python provides the return keyword to allow you to use a value that your function produces.

When you use return, you can assign the result of a function to a variable or use the function anywhere you would use that value.

When you return in a function, none of the additional lines in the function executes

def myfunction():
    return "Hello"

greeting = myfunction()
print(myfunction() + " , world")

In [ ]:
def cost_of_feed(type_of_feed):
    cost = None
    if type_of_feed == 'oats':
        cost = 20
    elif type_of_feed == 'corn':
        cost = 5
    elif type_of_feed == 'grass':
        cost = 0
    return cost

oats_cost = cost_of_feed('oats')

# Now I can use this value
oats_for_farm = 150 * oats_cost
print("It costs $" + str(oats_for_farm) + " to feed 150 horses")

Why would I use return instead of print? If you use print, you can only use what you print once, if you use return, you can store the value and use it somewhere else. You will want to use return almost every time.

TRY IT

Update your function ranch() from a previous try it to return the animal. Then call your function and store the result in a variable called 'animal'


In [ ]:

Why functions?

  1. Avoid repetition: If you find you are writing the same lines of code again and again, write a function instead. Then there is only one place that you have to check for errors or make changes to.

  2. Clarify actions: Instead of having a long series of lines, you can place related code into a named function. Then you can call the function instead and it makes your intent clearer. Name your functions clearly a() is short to type but you'll pay for that later when you forget what it means.

  3. Reuse: You can create your own modules with your functions and import them into you programs. Then you only have to write some functions once.

Project: Yahtzee roller

  1. Create a function called roll_die that returns a random number from 1-6.
  2. Create a function called yahtzee that rolls 5 dice. It should call roll die 5 times and save each to a different variable. Check if all five dice are equal to the same number, if so print 'Yahtzee!!'. Return the values of all five dice separated by commas in a string (remember to cast the values to strings).
  3. Call yahtzee 10 times and print the results each time.

If someone gets a yahtzee the first time they run their finished program, I'll bring cookies to the next meeting.


In [ ]: