#!/usr/bin/env python
# coding: utf-8
# ## Section 2.2: Writing your own function - I
# One of the built-in functions you have come across is the `len` function. It can take a list as it argument. As its output, it then returns the length of that list. A function, such as len, is invoked by including it in your program with the appropriate argument(s). Other ways to say that a function is invoked is to say that we run or call it.
# ### Activity
# Run the following Python program and note what happens:
# In[20]:
myList = ['a', 'b', 'c']
result = len(myList)
#
Though the program invokes the function `len`, nothing visible will have happened. But what did happen? By running the program, the value computed by the function got assigned to the variable result. The value, in this case 3, represents the length of myList. By creating a new code cell, entering `result` ten running the cell, you can display value of the result variable.
# ### Activity
# Add a single line to the program, so that now the value of result is printed to the screen when you run the program.
# In[21]:
myList = ['a', 'b', 'c']
result = len(myList)
#ADD A LINE OF CODE TO PRINT THE RESULT
# ## Building up a function
#
# Here is an example of the function as part of small program.
#
# First I define a small list:
# In[22]:
myList = ['a', 'b']
# Then I write a loop that will count the number of items in the list.
# In[23]:
result = 0
for i in myList:
result = result + 1
result
# I could change the contents of the cell where I define the contents of `myList`, run that cell, and then run the loop cell to count the members of the new list.
#
# Or I could put everything into one cell:
# In[24]:
myList = ['a', 'b']
result = 0
for i in myList:
result = result + 1
result
# What are the advantages of doing that?
#
# It's certainly more conveneient than having to run two cells. But what if I want to count the members of lists elsewhere in my notebook/program? THings could get *very* confusing then!
#
# How about we define a function that packages together a group of lines, does a caluculation, and then return the result?
# In[25]:
def listLength(inputList):
result = 0
for i in inputList:
result = result + 1
return result
# If you run the previous cell it will define a function that I can call to caluclate the length of my list. Remember, the notebook will display the value of the last item in the cell when you run it.
# In[26]:
myList = ['a', 'b', 'c', 'd']
listLength(myList)
# We can also assign the value returned from the function to a variable, and print that.
# In[15]:
myListLength= listLength(myList)
myOtherList = ['a', 'b', 'c', 'd', 'e', 'f']
myOtherListLength= listLength(myOtherList)
print(myList, myListLength)
print(myOtherList, myOtherListLength)
# In[27]:
set(dir()) - set(dir(__builtins__))
# In[28]:
get_ipython().run_line_magic('reset', '-f -s')
set(dir()) - set(dir(__builtins__))
# In[ ]: