02-Functions
02-Functions
___
Content Copyright by Pierian Data
1 Functions
1.1 Introduction to Functions
This lecture will consist of explaining what a function is in Python and how to create one. Functions
will be one of our main building blocks when we construct larger and larger amounts of code to
solve problems.
1
• adding in logic inside a function
• multiple returns inside a function
• adding in loops inside a function
• tuple unpacking
• interactions between functions
We begin with def then a space followed by the name of the function. Try to keep names relevant,
for example len() is a good name for a length() function. Also be careful with names, you wouldn’t
want to call a function the same name as a built-in function in Python (such as len).
Next come a pair of parentheses with a number of arguments separated by a comma. These
arguments are the inputs for your function. You’ll be able to use these inputs in your function and
reference them. After this you put a colon.
Now here is the important step, you must indent to begin the code inside your function correctly.
Python makes use of whitespace to organize code. Lots of other programing languages do not do
this, so keep that in mind.
Next you’ll see the docstring, this is where you write a basic description of the function. Using
Jupyter and Jupyter Notebooks, you’ll be able to read these docstrings by pressing Shift+Tab after
a function name. Docstrings are not necessary for simple functions, but it’s good practice to put
them in so you or other people can easily understand the code you write.
After all this you begin writing the code you wish to execute.
The best way to learn functions is by going through examples. So let’s try to go through examples
that relate back to the various objects and data structures we learned about before.
2
hello
If you forget the parenthesis (), it will simply display the fact that say_hello is a function. Later on
we will learn we can actually pass in functions into other functions! But for now, simply remember
to call functions with ().
[7]: say_hello
[2]: greeting('Jose')
Hello Jose
[5]: add_num(4,5)
[5]: 9
[7]: print(result)
9
What happens if we input two strings?
[8]: add_num('one','two')
[8]: 'onetwo'
3
1.4 Very Common Question: “What is the difference between return and
print?”
The return keyword allows you to actually save the result of the output of a function
as a variable. The print() function simply displays the output to you, but doesn’t save
it for future use. Let’s explore this in more detail
[9]: def print_result(a,b):
print(a+b)
[11]: print_result(10,5)
15
[13]: # You won't see any output if you run this in a .py script
return_result(10,5)
[13]: 15
But what happens if we actually want to save this result for later use?
[14]: my_result = print_result(20,20)
40
[15]: my_result
[16]: type(my_result)
[16]: NoneType
Be careful! Notice how print_result() doesn’t let you actually save the result to a
variable! It only prints it out, with print() returning None for the assignment!
[18]: my_result
[18]: 40
[19]: 80
4
2 Adding Logic to Internal Function Operations
So far we know quite a bit about constructing logical statements with Python, such as if/else/elif
statements, for and while loops, checking if an item is in a list or not in a list (Useful Operators
Lecture). Let’s now see how we can perform these operations within a function.
[20]: 2 % 2
[20]: 0
[21]: 20 % 2
[21]: 0
[22]: 21 % 2
[22]: 1
[23]: 20 % 2 == 0
[23]: True
[24]: 21 % 2 == 0
[24]: False
** Let’s use this to construct a function. Notice how we simply return the boolean check.**
[25]: def even_check(number):
return number % 2 == 0
[26]: even_check(20)
[26]: True
[27]: even_check(21)
[27]: False
5
[28]: def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a "hit" on an even number, we return True
if number % 2 == 0:
return True
# Otherwise we don't do anything
else:
pass
** Is this enough? NO! We’re not returning anything if they are all odds!**
[29]: check_even_list([1,2,3])
[29]: True
[30]: check_even_list([1,1,1])
** VERY COMMON MISTAKE!! LET’S SEE A COMMON LOGIC ERROR, NOTE THIS IS
WRONG!!!**
[31]: def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a "hit" on an even number, we return True
if number % 2 == 0:
return True
# This is WRONG! This returns False at the very first odd number!
# It doesn't end up checking the other numbers in the list!
else:
return False
[32]: False
** Correct Approach: We need to initiate a return False AFTER running through the entire loop**
[33]: def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a "hit" on an even number, we return True
if number % 2 == 0:
return True
# Don't do anything if its not even
else:
pass
6
# Notice the indentation! This ensures we run through the entire for loop ␣
↪
return False
[34]: check_even_list([1,2,3])
[34]: True
[35]: check_even_list([1,3,5])
[35]: False
even_numbers = []
return even_numbers
[37]: check_even_list([1,2,3,4,5,6])
[37]: [2, 4, 6]
[38]: check_even_list([1,3,5])
[38]: []
7
[40]: for item in stock_prices:
print(item)
('AAPL', 200)
('GOOG', 300)
('MSFT', 400)
AAPL
GOOG
MSFT
200
300
400
Similarly, functions often return tuples, to easily return multiple results for later use.
Let’s imagine the following list:
[58]: work_hours = [('Abby',900),('Billy',400),('Cassie',800)]
The employee of the month function will return both the name and number of hours worked for
the top performer (judged by number of hours worked).
[60]: employee_check(work_hours)
8
[60]: ('Abby', 900)
[49]: example
[49]: [5, 2, 4, 1, 3]
return mylist
[52]: mylist
[53]: shuffle_list(mylist)
guess = ''
9
return int(guess)
[55]: player_guess()
[55]: 0
Now we will check the user’s guess. Notice we only print here, since we have no need to save a
user’s guess or the shuffled list.
[56]: def check_guess(mylist,guess):
if mylist[guess] == 'O':
print('Correct Guess!')
else:
print('Wrong! Better luck next time')
print(mylist)
Now we create a little setup logic to run all the functions. Notice how they interact with each
other!
[57]: # Initial List
mylist = [' ','O',' ']
# Shuffle It
mixedup_list = shuffle_list(mylist)
10