Functions Flashcards
(37 cards)
What are Functions?
Functions allow us to reuse and organize code.
How do you calculate the area of a circle?
Example
radius = 5
area = 3.14 * radius * radius
How do you calculate multiple circles without having to rewrite the same code?
Define the function once and call the function every time I need that code. Functions help reuse code.
Example:
Instead, we can define a new function called area_of_circle using the def keyword.
def area_of_circle(r):
pi = 3.14
result = pi * r * r
return result
Let’s break this area_of_circle function down:
It takes one input (aka “parameter” or “argument”) called r
The body of the function is indented - this is the code that will run each time we use (aka “call”) the function
It returns a single value (the output of the function). In this case, it’s the value stored in the result variable
What is a Parameter?
The Parameter is the Input value in the define function.
Parameters are the names used for inputs when defining a function.
That said, this is all semantics, and frankly developers are really lazy with these definitions. You’ll often hear the words “arguments” and “parameters” used interchangeably.
Example:
a and b are parameters
def add(a, b):
return a + b
5 and 6 are arguments
sum = add(5, 6)
What is a Argument?
An argument is the Input value when the function is called.
Arguments are the values that are passed into the function by the caller
Arguments are the values of the inputs supplied when a function is called.
That said, this is all semantics, and frankly developers are really lazy with these definitions. You’ll often hear the words “arguments” and “parameters” used interchangeably.
Example:
a and b are parameters
def add(a, b):
return a + b
5 and 6 are arguments
sum = add(5, 6)
What does Call mean?
To “call” this function (fancy programmer speak for “use this function”) we can pass in any number as the argument.
We can define a new function called area_of_circle using the def keyword.
If the parameter is 5, it looks like below. Show how you would use different inputs now that we’ve defined the function.
Example:
def area_of_circle(r):
pi = 3.14
result = pi * r * r
return result
def area_of_circle(5):
pi = 3.14
result = pi * 5 * 5
return result
- 5 goes in as the input r
- The body of the function runs, which stores 78.5 in the result variable
- The function returns the value 78.5, which means the area_of_circle(5) expression evaluates to 78.5
- 78.5 is stored in the area variable and then printed
Example:
area = area_of_circle(5)
print(area)
# 78.5
Because we’ve already defined the function, now we can use it as many times as we want with different inputs!
Examples:
area = area_of_circle(6)
print(area)
# 113.04
area = area_of_circle(7)
print(area)
# 153.86
What does the body of a function look like?
The body of the function is indented - this is the code that will run each time we use (aka “call”) the function
It is 4 spaces indented. Depending on what Python interpreter you’re using, it may automatically indent for you.
def area_of_circle(radius):
pi = 3.14
area = pi * radius * radius
return area
How would you calculate a weapon’s “attack area”?
With a 1.0 meter sword, for example, a player can attack in an area of 3.14 square meters around them.
You can use the area_of_circle function to do that calculation.
What happens first in a Function?
The Function is defined.
Let’s break down this function line by line so you can understand every nook and cranny of it.
def area_of_circle(r):
pi = 3.14
result = pi * r * r
return result
radius = 5
area = area_of_circle(radius)
print(area)
# 78.5
Here’s a chronological explanation of what happens when the above code is executed:
- def area_of_circle(r)
The area_of_circle function is defined for later use, but not called. It accepts a single input, the arbitrarily named r. The body of the function (pi = 3.14… etc) is ignored for now. - radius = 5
A new variable called radius is created and set to the value 5. - area_of_circle(radius)
The area_of_circle function is called with radius (in this case 5) as the input. Finally, we jump back to the function definition. - def area_of_circle(r):
We will now start executing the body of the function, and r is set to 5. - pi = 3.14
A new variable called pi is created with a value of 3.14. - result = pi * r * r
Some simple math is evaluated (3.14 * 5 * 5) and stored in the result variable. - return result
The result variable is returned from the function as output. - area = area_of_circle(radius)
The returned value is stored in a new variable called area (in this case 78.5). - print(area)
The value of area is printed to the console.
What is the last step once the code Function is executed?
A value is returned from the function.
Why is the variable called ‘radius’ outside the function, but ‘r’ inside the function?
Because only the value of the variable is passed to the function. It is then assigned to a new variable called “r”.
Can Functions have Multiple Parameters?
Yes, Functions can have Multiple Parameters
For example, this subtract function accepts 2 parameters: a and b.
def subtract(a, b):
result = a - b
return result
Does the name of the Parameter matter when using Multiple Parameters in a Function?
No. The name of a parameter doesn’t matter when it comes to which values will be assigned to which parameter.
What matters when it comes to the parameters when using Multiple Parameters in a Function?
The POSITION matters!
The first parameter will become the first value that’s passed in, the second parameter is the second value that’s passed in, and so on.
In this example, the subtract function is called with a = 5 and b = 3:
result = subtract(5, 3)
print(result)
# 2
—–
Here’s an example with four parameters:
def create_introduction(name, age, height, weight):
first_part = “Your name is “ + name + “ and you are “ + age + “ years old.”
second_part = “You are “ + height + “ meters tall and weigh “ + weight + “ kilograms.”
full_intro = first_part + “ “ + second_part
return full_intro
It can be called like this:
my_name = “John”
my_age = “30”
intro = create_introduction(my_name, my_age, “1.8”, “80”)
print(intro)
# Your name is John and you are 30 years old. You are 1.8 meters tall and weigh 80 kilograms.
We need to calculate the total damage from a combo of three damaging attacks.
Complete the triple_attack function by returning the sum of its parameters, damage_one, damage_two, and damage_three.
def triple_attack(damage_one, damage_two, damage_three):
total = damage_one + damage_two + damage_three
return total
What is the difference between Printing and Returning?
print() is a function that:
- Prints a value to the console
- Does not return a value
return is a keyword that:
- Ends the current function’s execution
- Provides a value (or values) back to the caller of the function
- Does not print anything to the console (unless the return value is later print()ed)
Print: Shows a value in the console.
Return: Makes a value available to the caller of the function.
Is Printing a good way to Debug your code?
Printing values and running your code is a great way to debug your code. You can see what values are stored in various variables, find your mistakes, and fix them. Add print statements and run your code as you go! It’s a great habit to get into to make sure that each line you write is doing what you expect it to do.
In the real world it’s rare to leave print() statements in your code when you’re done debugging.
Where do you Declare Functions?
NameError: ‘my_name’ is not defined
You’ve probably noticed that a variable needs to be declared before it’s used.
Code executes in order from top to bottom, so a variable needs to be created BEFORE it can be used. That means that if you define a function, you CAN’T CALL that function until AFTER it has been defined.
For example, the following doesn’t work:
print(my_name)
my_name = ‘Lane Wagner’
It needs to be:
Code executes in order from top to bottom, so a variable needs to be created before it can be used. That means that if you define a function, you can’t call that function until AFTER it has been defined.
What does Declare mean in Python?
In Python, we don’t “declare” variables, we simply assign them. In short, we can think of a variable in Python as a name for an object
The Order of Functions MUST be ___ before they can be ___?
The Order of Functions MUST be DEFINED before they can be CALLED.
All functions must be defined before they’re used.
You might think this would make structuring Python code hard because the order of the functions needs to be just right. As it turns out, there’s a simple trick that makes it super easy.
Most Python developers solve this problem by defining all the functions in their program first, then they call an “entry point” function last. That way all of the functions have been read by the Python interpreter before the first one is called.
Example: Conventionally this “entry point” function is usually called main to keep things simple and consistent.
def main():
health = 10
armor = 5
add_armor(health, armor)
def add_armor(h, a):
new_health = h + a
print_health(new_health)
def print_health(new_health):
print(f”The player now has {new_health} health”)
call entrypoint last
main()
TRUE OR FALSE: Functions must be defined in the order that they call each other.
FALSE
Define all the functions in their program FIRST, then they CALL an “entry point” function LAST.
That way all of the functions have been read by the Python interpreter before the first one is called.
Which is best practice to make sure you don’t define functions out of order?
Create an entrypoint function (usually called main) and call it at the end of the file.
Example:
def main():
health = 10
armor = 5
add_armor(health, armor)
def add_armor(h, a):
new_health = h + a
print_health(new_health)
def print_health(new_health):
print(f”The player now has {new_health} health”)
call entrypoint last
main()