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.
Run the following Python program and note what happens:
myList = ['a', 'b', 'c']
result = len(myList)
Add a single line to the program, so that now the value of result is printed to the screen when you run the program.
myList = ['a', 'b', 'c']
result = len(myList)
#ADD A LINE OF CODE TO PRINT THE RESULT
Here is an example of the function as part of small program.
First I define a small list:
myList = ['a', 'b']
Then I write a loop that will count the number of items in the list.
result = 0
for i in myList:
result = result + 1
result
2
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:
myList = ['a', 'b']
result = 0
for i in myList:
result = result + 1
result
2
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?
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.
myList = ['a', 'b', 'c', 'd']
listLength(myList)
4
We can also assign the value returned from the function to a variable, and print that.
myListLength= listLength(myList)
myOtherList = ['a', 'b', 'c', 'd', 'e', 'f']
myOtherListLength= listLength(myOtherList)
print(myList, myListLength)
print(myOtherList, myOtherListLength)
['a', 'b', 'c', 'd'] 4 ['a', 'b', 'c', 'd', 'e', 'f'] 6
set(dir()) - set(dir(__builtins__))
{'In', 'Out', '_', '_19', '_23', '_24', '_26', '__', '___', '__builtin__', '__builtins__', '_dh', '_i', '_i20', '_i21', '_i22', '_i23', '_i24', '_i25', '_i26', '_i27', '_ih', '_ii', '_iii', '_oh', '_sh', 'exit', 'i', 'listLength', 'myList', 'quit', 'result'}
%reset -f -s
set(dir()) - set(dir(__builtins__))
{'In', 'Out', '_', '_19', '_23', '_24', '_26', '_27', '__', '___', '__builtin__', '__builtins__', '_dh', '_i', '_i20', '_i21', '_i22', '_i23', '_i24', '_i25', '_i26', '_i27', '_i28', '_ih', '_ii', '_iii', '_oh', '_sh', 'exit', 'quit'}