

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 8
click for more info
Not enough gems
Cost: 6 gems
1: Functions
incomplete
2: Function Review
incomplete
3: Multiple Parameters
incomplete
4: Printing vs. Returning
incomplete
5: Where to Declare Functions
incomplete
6: Order of Functions
incomplete
7: Community
incomplete
8: Boots Interview
incomplete
9: Solutions
incomplete
10: None Return
incomplete
11: Multiple Return Values
incomplete
12: Parameters vs. Arguments
incomplete
13: Default Values
incomplete
14: Curse
incomplete
15: The Training Grounds
incomplete
16: Enchant and Attack
incomplete
17: Archmage
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Functions let us reuse and organize code. Say we have some code that calculates the area of a circle:
radius = 5
area = 3.14 * radius * radius
That works! The problem is when we want to calculate the area of other circles, each with its own radius. We could just copy the code and change the variable names like this:
radius = 5
area1 = 3.14 * radius * radius
radius2 = 7
area2 = 3.14 * radius2 * radius2
But we want to reuse our code! Who wants to redo the same work?!? What if we wanted to calculate the area of thousands of circles??? That's where functions help.
Instead, let's 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
r:, the indented lines form the function body, that is, the code that runs each time we use (aka "call") the functionreturns (outputs) a single value. In this case, the value stored in the result variableTo "call" this function (fancy programmer speak for "use this function") we can pass in any number as the argument (in this case, 5) for the parameter r, and capture the output into a new variable:
area = area_of_circle(5)
print(area)
# 78.5
5 goes in as the input r78.5 in the result variable in the function bodyresult variable, meaning the area_of_circle(5) expression evaluates to 78.578.5 is stored in the area variable and then printedBecause we've already defined the function, now we can use it as many times as we want with different inputs!
area = area_of_circle(6)
print(area)
# 113.04
area = area_of_circle(7)
print(area)
# 153.86
Try calling the function yourself and watch the body run:
Interactive example available with JavaScript enabled.
We need to calculate the size of 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.
Fix the bug where spear_area is 0 by calling the area_of_circle function with the spear_length as input and store the result in the spear_area variable.