Today we will be covering functions and scope of variables!
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.
Here is an example of a function so you can get an idea of the general format:
# this is a function that takes 2 parameters and prints the values
def my_function(parameter_a, parameter_b): # this is known as the Function Signature
print("Inside my_function!")
print("The value of parameter_a is", parameter_a)
print("The value of parameter_b is", parameter_b)
Above there is a function definition called my_function
. my_function
takes 2 values and prints some stuff, but it only prints when the function is called.
Below is an example of calling a function:
my_function(6, 700000000) # calling my_function
Inside my_function! The value of parameter_a is 6 The value of parameter_b is 700000000
Important: We say that the values 6 and 700000000 are being passed to the function my_function
.
def my_function(parameter_a, parameter_b):
print("Inside my_function!")
print("The value of parameter_a is", parameter_a)
print("The value of parameter_b is", parameter_b)
# print(f"printing parameter_a: {parameter_a}")
# print(f"printing parameter_b: {parameter_b}")
my_function(6, 700000000)
Inside my_function! The value of parameter_a is 6 The value of parameter_b is 700000000
The error that we see from running the above code is NameError: name 'parameter_a' is not defined
. What does that mean in this context? Just a couple of lines above this code cell we printed the variables parameter_a
and parameter_b
without issue.
What changed?
The difference is that parameter_a
and parameter_b
were defined inside of my_function
when we called it because we assigned them the values 6 and 700000000, but outside of my_function
, parameter_a
and parameter_b
have not been assigned a value and so they are undefined.
The issue we are encountering is that we are trying to use the variables,
parameter_a
and parameter_b
, outside of their scope. Scope is the area of the program that a variable, constant, or function, that has an identifier name is recognized. Inside of my_function
, parameter_a
and parameter_b
are recognized, but outside of the function those variables are not recognized.
The way a function's scope is defined is by using indentations the same way that if
statement blocks are defined.
my_function
.# call my_function with new values in this cell!
my_function()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-28777a0eaee1> in <module>() 1 # call my_function with new values in this cell! 2 ----> 3 my_function() TypeError: my_function() missing 2 required positional arguments: 'parameter_a' and 'parameter_b'
Call my_function with different values other than 6 and 700000000.
Note: You don't have to use numbers only, you can use words, too!
Let's define a more interesting function that actually does something with the parameters and returns that value back to us.
# function definition
def add_numbers(num_1, num_2):
return num_1 + num_2
returned_value = add_numbers(2, 2) # You can store return values in variables
print("2 + 2 equals: ", returned_value) # can use them just like normal variables
2 + 2 equals: 4
The code above shows us how we can use functions to return values back to us after we call them. The way we do that is by using the keyword return.
# function definition
def add_numbers(num_1, num_2, num_3): # Added an additional parameter
return num_1 + num_2
returned_value = add_numbers(2, 2) # Fix me!!!
print("The return value from add_numbers equals:", returned_value) # can use them just like normal variables
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-da5a54723568> in <module>() 4 5 ----> 6 returned_value = add_numbers(2, 2) # Fix me!!! 7 8 print("The return value from add_numbers equals:", returned_value) # can use them just like normal variables TypeError: add_numbers() missing 1 required positional argument: 'num_3'
Use the added parameter num_3 in the function add_numbers
however you like. You could use it in a print statement, or add it to the equation that is being returned.
Fix the error.
Hint: Read the comment in the cell
def personal_info(age, birthday_month, hometown, name):
print("Hi! my name is: ", name)
print("My birthday month is:", birthday_month)
print("My hometown is:", hometown)
print("I am: ", age)
# Call the function personal_info here!
Hi! my name is: kass My birthday month is: blach My hometown is: oregon I am: 23
Call the function personal_info
with the correct values to let us know a bit more about you.
Hint: Order matters with parameters. If your values are printing out wrong, check how you are passing your values to the function.
# define the function my_first_function below
Above define the function my_first_function
.
This function will take 0 parameters, so it will look like this: def example():
Have this function print
out the phrase Computer Science is the best!
and not have a return statement.
Hint: keep in mind indentation!
Run the code cell below to see if your function works!
# Run me!
my_first_function()
Computer Science is the best!
# Your code here!
# def name_check(name):
In the cell above, write a function that takes a name variable and checks to see if the name is the same as your name. if
it is the same, return True, else
return False.
Hint: you can compare words like this "Kassidy" == "Kassidy"
Run the code below to see if your name_check
function works.
name = "Kassidy"
if name_check(name):
print("The names are the same!")
else:
print("Not the same")
Not the same
name
variable from "Kassidy" to your name to make sure the function works properly.You can also call functions from inside other functions. Below is an example of this.
def called_function():
print("Some other function is calling me!")
def outer_function(): # The only thing this function does is call called_function
called_function()
# We are calling outer_function here
outer_function()
Some other function is calling me!
The above example shows us that functions can use other functions. We will explore why this is useful below.
# This function checks to see if someone is a teenager
def teenager_check(age):
if age >= 13 and age <= 19:
return True
else:
return False
def can_drive(age):
is_teen = teenager_check(age)
if is_teen and age >= 16:
print("I am old enough to drive and I'm a teen!")
else:
print("Can't drive quite yet or you're not a teen!")
def can_vote(age):
is_teen = teenager_check(age)
if is_teen == True and age >= 18:
print("I'm a teen, but I am old enough to vote!")
else:
print("Guess I'm not old enough to vote or I'm not a teen!")
age = 0 #change to your age!
can_drive(age)
Can't drive quite yet or you're not a teen!
can_drive
and teenager_check
. age = 0 # Change me to your age!
can_vote(age)
Guess I'm not old enough to vote or I'm not a teen!
can_vote
when you're a different age. By using the function teenager_check
we are able to do 2 really important things:
teenager_check
We called the function teenage_check
in can_drive
and in can_vote
. We were able to write the code once and use it twice, which is great! The lazier we can be the better!
import matplotlib.pyplot as plt
# The below function plots the ratings associated with a list of your choosing!
# You don't need to care about this code, you won't be make direct changes to it.
def show_ratings(names, values, label):
plt.figure(figsize=(10, 5))
plt.subplot()
plt.bar(names, values, color="springgreen")
plt.suptitle(label)
plt.show()
Above, we have a function that will plot the ratings for things of our choosing. In the simple example below we are using this function to plot the ratings for foods.
Important: Notice that we are passing lists to the function show_ratings
and not numbers or words.
# Run me to see show_ratings in action!
foods = ['Pizza', 'Hamburgers', 'Broccoli']
ratings = [100, 10, 2]
label = "Food Ratings"
show_ratings(foods, ratings, label)
# Write code!
# Create a list of words that represent things you want to be rated.
names = []
# Create a list of ratings
ratings = []
# Create a label for your bargraph
label = ""
# Call the function show_ratings with the variables you just created
In the above cell follow the example that is just above to create your own graph.
Important: Remember to call the function with your parameters
At this point the power of functions is probably clear to you now. The ability to write the code once and use it as many times as you need is incredibly powerful. Imagine how many things you can rate now! Foods, movies, books! The possibilities are endless.
# Write code here!
show_ratings
again to rate some stuff of your choosing (feel free to reuse the code you already wrote above), but this time change the lists to have 5 items instead of 3. # Write code here!
def sum_list(numbers):
File "<ipython-input-106-53aa0d8dcf7a>", line 4 ^ SyntaxError: unexpected EOF while parsing
In the above code cell, write a function that takes a list as a parameter and adds all of the values in the list. Return the sum.
Important: Use a loop of some kind and write your function so the list can be of any length.
Run the below cell to see if your function works.
test_numbers = [4, 6, 7, 8, 9]
sum_test_numbers = sum_list(test_numbers)
print("the sum of test_numbers should be 34 and is:", sum_test_numbers)
the sum of test_numebrs should be 34 and is: 34
def calculate(numbers):
total_subtract = 0
total_addition = 0
# Your code here:
return (total_subtract, total_addition)
total_addition
.In the same function, write code that subtracts all of the values and stores the total in total_subtract
.
Hint: Is there a function that you wrote that you could you to help you with this function?
Important: In Python, functions can return more than one value!
numbers = [3.14, 6, 9, 10.0, 111, 42, 6]
total_sub, total_add = calculate(numbers)
print("The total for subtraction: ", total_sub)
print("The total for addition: ", total_add)
The total for subtraction: -187.14 The total for addition: 187.14
calculate
def even_list(starting_value, ending_value):
evens = []
#Your code goes here
while starting_value <= ending_value:
evens += [starting_value]
starting_value += 2
return evens
Above, define a function that returns a list of all of the even numbers from starting_value to ending_value. Use a loop!
Example:
starting_value = 2
ending_value = 10
evens = [2, 4, 6, 8, 10]
evens = even_list(2, 30)
print("Correct Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]")
print("Your Output:", evens)
Correct Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30] Your Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
even_list
function!Write the code to find the maximum or minimum value of a list of numbers depending on a second parameter which is a word with the value "max" or "min". If the second parameter is "max" return the maximum value of the list. If the second parameter is "min" return the minimum value of the list.
Hints:
Important: If you want to call a function from find_min_or_max
, it must be defined above it.
# Start here -- define more functions if you'd like
def find_min_or_max(numbers, max_or_min):
# Run testing code below to check your work!
numbers = [5, 6, 10, 100, 99, 23, 1, 0, 55, -22]
min = find_min_or_max(numbers, "min")
max = find_min_or_max(numbers, "max")
print("The minimum is:", min)
print("The maximum is:", max)
The minimum is: -22 The maximum is: 100
Write a function that takes a single word as a parameter like "Code" and returns a new value like "CCoCodCode".
Examples:
word_splosion('Code') → 'CCoCodCode'
word_splosion('abc') → 'aababc'
word_splosion('ab') → 'aab'
Important: To solve this problem you need to learn how to use len(word). It's pretty easy - the way the len() function works is you pass it a word and it tells you how long it is. Run the examples below to see how it works in action.
print(len("Kassidy"))
7
phrase = "I'm a little teapot"
print(len(phrase))
19
Note: The len() function counts spaces too.
# Fill in code here!
def word_splosion(word):
File "<ipython-input-163-0c4075dea0c8>", line 4 ^ SyntaxError: unexpected EOF while parsing
# Run to test word_splosion
print("Should be: CCoCodCode")
print("Is:", word_splosion("Code"))
print("Should be: CCoComCompCompuComputComputeComputerComputersComputers!")
print("Is:", word_splosion("Computers!"))
Should be: CCoCodCode Is: CCoCodCode Should be: CCoComCompCompuComputComputeComputerComputersComputers! Is: CCoComCompCompuComputComputeComputerComputersComputers!