Lesson 6 of 7
Functions
Organise and reuse code effortlessly by defining and calling custom Python functions.
Learn it
Imagine having a magic spell that does five cool things every time you say one word. In programming, that magic spell is called a function!
Instead of writing the same ten lines of code again and again, you wrap them into a function with a name. Whenever you need those actions, you simply call that function name.
Key terms
- Function
- A named, reusable block of code designed to perform a specific action.
- Parameter
- A variable listed inside a function definition that receives incoming input data.
- Argument
- The actual value passed into a function when it is called.
- Return Value
- The final output or result that a function sends back to the code that called it.
Lifecycle of a Function Call
Understand how data flows into, through, and back out of a Python function.
- 1Definition (def): The function structure and parameter list are defined and stored in memory.
- 2Invocation (Call): The main program calls the function by name, passing specific values (arguments).
- 3Local Processing: The function body runs using the parameter values to compute an outcome.
- 4Returning Data: The return keyword delivers the computed result back to the caller for further use.
Calculating Attack Damage with a Function
pythondef calculate_damage(base_attack, crit_multiplier):
total_damage = base_attack * crit_multiplier
return total_damage
hit_one = calculate_damage(20, 2)
print("Critical hit dealt:", hit_one)
hit_two = calculate_damage(15, 1)
print("Normal hit dealt:", hit_two)We define calculate_damage once, then call it twice with different arguments to compute distinct damage numbers.
Try it
Evaluate whether these statements about Python functions are true or false.
Functions must be defined with the def keyword before they can be called in your code.
A function can only ever be called once in an entire Python program.
The return keyword allows a function to send a calculated result back to the caller.
Parameters and arguments are used to pass information into functions.
Challenge
Define a function named calculate_area that takes two parameters (width, height) and returns width * height.
Pick whichever way suits you — every mode earns the same bonus XP.
Write at least 40 more characters to submit.
Mark your own work
Guided walkthrough — 0/5 clues revealed
- Clue 1 locked — reveal it only if you get stuck.
- Clue 2 locked — reveal it only if you get stuck.
- Clue 3 locked — reveal it only if you get stuck.
- Clue 4 locked — reveal it only if you get stuck.
- Clue 5 locked — reveal it only if you get stuck.
Each clue costs 5 XP (never below 25 XP). You'd earn 50 XP right now.
Extension: Call your function three times with different room dimensions and print each room's area.