Functions Flashcards

(37 cards)

1
Q

What are Functions?

A

Functions allow us to reuse and organize code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you calculate the area of a circle?

A

Example
radius = 5
area = 3.14 * radius * radius

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you calculate multiple circles without having to rewrite the same code?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a Parameter?

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a Argument?

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does Call mean?

A

To “call” this function (fancy programmer speak for “use this function”) we can pass in any number as the argument.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does the body of a function look like?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

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.

A

You can use the area_of_circle function to do that calculation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What happens first in a Function?

A

The Function is defined.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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

A

Here’s a chronological explanation of what happens when the above code is executed:

  1. 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.
  2. radius = 5
    A new variable called radius is created and set to the value 5.
  3. 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.
  4. def area_of_circle(r):
    We will now start executing the body of the function, and r is set to 5.
  5. pi = 3.14
    A new variable called pi is created with a value of 3.14.
  6. result = pi * r * r
    Some simple math is evaluated (3.14 * 5 * 5) and stored in the result variable.
  7. return result
    The result variable is returned from the function as output.
  8. area = area_of_circle(radius)
    The returned value is stored in a new variable called area (in this case 78.5).
  9. print(area)
    The value of area is printed to the console.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the last step once the code Function is executed?

A

A value is returned from the function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Why is the variable called ‘radius’ outside the function, but ‘r’ inside the function?

A

Because only the value of the variable is passed to the function. It is then assigned to a new variable called “r”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Can Functions have Multiple Parameters?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Does the name of the Parameter matter when using Multiple Parameters in a Function?

A

No. The name of a parameter doesn’t matter when it comes to which values will be assigned to which parameter.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What matters when it comes to the parameters when using Multiple Parameters in a Function?

A

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.

17
Q

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.

A

def triple_attack(damage_one, damage_two, damage_three):
total = damage_one + damage_two + damage_three
return total

18
Q

What is the difference between Printing and Returning?

A

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.

19
Q

Is Printing a good way to Debug your code?

A

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.

20
Q

Where do you Declare Functions?

A

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.

21
Q

What does Declare mean in Python?

A

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

22
Q

The Order of Functions MUST be ___ before they can be ___?

A

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()

23
Q

TRUE OR FALSE: Functions must be defined in the order that they call each other.

A

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.

24
Q

Which is best practice to make sure you don’t define functions out of order?

A

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()

25
Example Problem In Fantasy Quest, characters lose health due to heat exhaustion. The game tracks the temperature in Freedom units (Fahrenheit), but we need to display the temperature in Celsius for players outside the US. Here's the formula to calculate the temperature in Celsius from Fahrenheit (f): 5/9 * (f - 32) Complete the to_celsius function body. It should return the temperature in Celsius for a given Fahrenheit temperature (f parameter).
def to_celsius(f): c = 5 / 9 * (f - 32) return c
26
Which keyword is used to create functions in Python?
def
27
A function must be defined ____ to be called many times with different arguments.
A function must be defined ONCE to be called many times with different arguments.
28
Example Problem: We need to display the current time to our players. The problem is that the time is stored as a number of hours, but we want to display it as a number of seconds. There are 60 seconds in a minute, but how many are in an hour? Complete the hours_to_seconds function. It should convert hours to seconds and return the result.
def hours_to_seconds(hours): return hours * 60 * 60
29
What happens if there is no 'return' line in a function?
It returns None. When no return value is specified in a function, it will automatically return None. For example, maybe it's a function that prints some text to the console, but doesn't explicitly return a value. The following code snippets all return the same value, None: def my_func(): print("I do nothing") return None def my_func(): print("I do nothing") return def my_func(): print("I do nothing")
30
How do you get Multiple Return Values?
A function can return more than one value by separating them with commas. Example: def cast_iceblast(wizard_level, start_mana): damage = wizard_level * 2 new_mana = start_mana - 10 return damage, new_mana # return two values
31
Receiving Multiple Values
When calling a function that returns multiple values, you can assign them to multiple variables. dmg, mana = cast_iceblast(5, 100) print(f"Damage: {dmg}, Remaining Mana: {mana}") # Damage: 10, Remaining Mana: 90 When cast_iceblast is called, it returns two values. The first value is assigned to dmg, and the second value is assigned to mana. Just like function inputs, it's the order of the values that matters, not the variable names. We could just as easily called the variables one and two: one, two = cast_iceblast(5, 100) print(f"Damage: {one}, Remaining Mana: {two}") # Damage: 10, Remaining Mana: 90 That said, descriptive variable names make your code easy to understand, so use them! --- What Happened to the Variables? The damage and new_mana variables from cast_iceblast's function body only exist INSIDE of the function. They can't be used outside of the function. We'll explain that more later when we talk about scope.
32
Example Problem: Complete the become_warrior function. It accepts 2 inputs: the full_name string, and the power integer. It should return 2 values: a "title" string and a "new power" integer. Create the title using f-strings. Combine full_name with "the warrior" in this format: full_name the warrior Create the new_power value that is equal to the input power plus one. Return both title and new_power For example: title, power = become_warrior("Aang Airbender", 100) print(title) # "Aang Airbender the warrior" print(power) # 101
def become_warrior(full_name, power): title = f"{full_name} the warrior" new_power = power + 1 return title, new_power
33
What are Default Values?
In Python you can specify a default value for a function argument. It's nice for when a function has arguments that are "optional". You as the function definer can specify a specific default value in case the caller doesn't provide one. A default value is created by using the assignment (=) operator in the function signature. Examples: def get_greeting(email, name="there"): print("Hello", name, "welcome! You've registered your email:", email) get_greeting("lane@example.com", "Lane") # Hello Lane welcome! You've registered your email: lane@example.com get_greeting("lane@example.com") # Hello there welcome! You've registered your email: lane@example.com If the second parameter is omitted, the default "there" value will be used in its place. As you may have guessed, for this structure to work, optional arguments (the ones with defaults) must come after all required arguments.
34
Example Problem: Complete the get_punched and get_slashed functions. They should both: - Take 2 integers as arguments, health and armor - Change the armor parameter to have a default value of 0 get_punched - Create a damage variable equal to 50 minus the armor - the armor reduces the damage - Create a new_health variable equal to the input health minus damage - we apply the damage - Return new_health get_slashed - Create a damage variable equal to 100 minus the armor - Create a new_health variable equal to the input health minus damage - Return new_health
def get_punched(health, armor=0): damage = 50 - armor new_health = health - damage return new_health def get_slashed(health, armor=0): damage = 100 - armor new_health = health - damage return new_health
35
How do you get a percentage of a number?
You can multiply a number by a decimal to get a percentage of a number. For example: 30% of 50 is 50 * 0.3
36
Example Problem: Curse: An enemy's weapons can be cursed so that they don't deal as much damage. Assignment: Complete the curse function. It accepts a weapon_damage parameter and returns two values: 1 - The lesser_cursed damage: reduce the input weapon_damage from 100% to 50% (50% - reduction). 2 - The greater_cursed damage: reduce the input weapon_damage from 100% to 25% (75% reduction). A greater curse is more powerful than a lesser curse, so it reduces the damage more.
def curse(weapon_damage): lesser_cursed = weapon_damage * 0.5 greater_cursed = weapon_damage * 0.25 return lesser_cursed, greater_cursed
37
Example Problem: In Fantasy Quest, a weapon can be enchanted to do bonus damage. Assignment: Complete the enchant_and_attack function. It creates a new "enchanted" name for a weapon and calculates how much damage the enchanted weapon will deal to a targeted enemy. It accepts 3 parameters: - target_health: integer - damage: integer - weapon: string It should do the following things in the function body: - Calculate and store the "enchanted damage" in a new variable. The enchanted damage should be the input damage plus 10. - Calculate and store the "new health" in a new variable. The new health should be the input target_health minus the enchanted damage. - Create a new variable called enchanted_weapon. It should be the input weapon with the string "enchanted " added to the beginning of it. For example: - sword -> enchanted sword - axe -> enchanted axe Return the enchanted weapon and the new health in that order.
def enchant_and_attack(target_health, damage, weapon): enchanted_damage = damage + 10 new_health = target_health - enchanted_damage enchanted_weapon = f"enchanted {weapon}" return enchanted_weapon, new_health