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".
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))
In [ ]:
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')
In [ ]:
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)
In [ ]:
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))
In [ ]:
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()
In [ ]:
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')
In [ ]:
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")
In [ ]:
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.
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.
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.
roll_die
that returns a random number from 1-6.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). If someone gets a yahtzee the first time they run their finished program, I'll bring cookies to the next meeting.
In [ ]: