Learn to create your own functions with parameters and return values to organize your code.
Think about a pizza recipe. You write it down once on a sheet of paper, and then you can use it whenever you want, you do not have to reinvent it every time you get hungry. That is exactly how functions work in Python. You write a set of instructions once, give it a name, and then you can use it as many times as you need, anywhere in your program.
Up until now you have already been using functions without knowing it, print(), input(), len() are all functions that someone else wrote for you. In this lesson, you will learn to create your own functions. It is like going from following recipes in someone else's cookbook to writing your own cookbook.
The Python Kingdom game code has grown a lot. It is time to organize it! In this lesson you will refactor the game into clean, reusable functions. You will create functions for hero creation, attack, inventory, and the main menu, making the code clearer and easier to extend.
A function is a block of code that does one specific thing and that you can reuse. Think of it as a pizza-making machine: you give it the ingredients (the input), it does the work, and it gives you the finished pizza (the result).
Why are functions useful? Three main reasons:
calculate_pizza_price(), you immediately know what that piece of code does, even without seeing the details.To create a function in Python, you use the keyword def, followed by the function name, parentheses, and a colon. All the code that belongs to the function must be indented (moved to the right with a Tab or 4 spaces):
This function is called greet_customer. Every time you call it, it will display the two messages. But be careful, just defining the function does not do anything. You also need to call it:
Result:
Welcome to Pizzeria Python!
What pizza would you like today?You can call the function as many times as you want:
One important thing: the function must be defined before it is called. If you try to call greet_customer() before the def block, Python will not know what you are talking about and will throw a NameError.
Our greeting function is fine, but it is a bit rigid, it says the same thing every time. What if we could tell it who to greet? This is where parameters come in.
Parameters are special variables that you place between the function parentheses. They receive values when you call the function:
Result:
Hello, Andrew!
Welcome to Pizzeria Python!
Hello, Maria!
Welcome to Pizzeria Python!Notice how name receives the value "Andrew" in the first call and "Maria" in the second. The parameter is like a blank spot in a recipe that you fill in with whatever you need.
You can have multiple parameters, separated by commas:
Result:
Your order: large pizza
Crust type: thin
Your order: medium pizza
Crust type: fluffyThe order matters: the first argument you pass goes to the first parameter, the second to the second, and so on.
So far, our functions only displayed things on the screen with print(). But sometimes you want a function to calculate something and give the result back so you can use it further in your code. For that you use return.
The difference is important: print() puts text on the screen for you to see. return sends a value back to the code that called the function, so you can do something with it.
Result:
The price of your pizza is: 36 dollarsWithout return, the function would return None (meaning nothing). Here is what happens if you forget return:
Remember: return also stops the function. Any code written after return will never execute:
The real power of functions appears when you combine them. Each function does one single thing, and then you use them together like puzzle pieces. Let's build a small pizza ordering system:
Result:
Order total: 47 dollarsNotice how elegant this is: calculate_total does not know how the base price or the toppings cost is calculated. It just calls the other two functions and combines their results. Each function has a single responsibility, just like in a kitchen where each chef has their own role.
Sometimes, a function has a parameter that most of the time receives the same value. Instead of specifying it every time, you can give it a default value:
Result:
Pizza large with thin crust
Drink: fanta
Pizza medium with regular crust
Drink: cola
Pizza small with regular crust
Drink: spriteThe rule is simple: parameters without a default value come first, those with a default value come last. This way Python knows what is required and what is optional.
Notice the last call: order_pizza("small", drink="sprite"). When you specify the parameter name (drink="sprite"), you can skip the parameters in between that have default values. These are called named arguments and they are very useful when you have functions with many parameters.
Functions are reusable blocks of code that you define with def, give a name to, and call whenever you need them. Parameters allow functions to receive different data on each call, and return sends the result back to the code that called the function. When you combine small, specialized functions, you can solve complex problems while keeping your code clean and easy to understand.
Write a function create_hero() that asks the player for their name and class (via input()), applies the class bonuses, and returns all of the hero's stats. The function should return: hero_name, hero_class, hp, attack, defense, gold. Call it and display the hero sheet with the returned values.
FUNCTION create_hero():
READ hero_name
READ class_choice (1/2/3)
SET hp = 100, attack = 15, defense = 10, gold = 50
IF class_choice == "1":
hero_class = "Warrior", hp += 20, attack += 5
ELSE IF class_choice == "2":
hero_class = "Mage", hp += 5, attack += 10
ELSE:
hero_class = "Archer", attack += 7, defense += 5
RETURN hero_name, hero_class, hp, attack, defense, gold
# Call the function
SET name, cls, hp, atk, dfs, gld = create_hero()
DISPLAY hero sheetWrite a function calculate_attack(attacker_atk, defender_hp, defender_def) that calculates the damage (attack - defense, minimum 1), subtracts it from the defender's HP, and returns the new HP and the damage dealt. Test it: a hero with 25 attack hits a monster with 40 HP and 5 defense. Display the damage and the monster's remaining HP.
FUNCTION calculate_attack(attacker_atk, defender_hp, defender_def):
SET damage = attacker_atk - defender_def
IF damage < 1:
damage = 1
SET new_hp = defender_hp - damage
RETURN new_hp, damage
# Test
SET monster_hp, dmg = calculate_attack(25, 40, 5)
DISPLAY "Damage: {dmg}, Remaining HP: {monster_hp}"Write two functions: (1) show_inventory(inventory) that receives a list and displays each item numbered, or "Inventory is empty." if the list is empty; (2) show_stats(name, hero_class, hp, max_hp, attack, defense, gold) that displays the hero's stats nicely formatted. Test both functions.
FUNCTION show_inventory(inventory):
IF length(inventory) == 0:
DISPLAY "Inventory is empty."
ELSE:
FOR i IN range(length(inventory)):
DISPLAY (i+1) + ". " + inventory[i]
FUNCTION show_stats(name, cls, hp, max_hp, atk, dfs, gold):
DISPLAY "--- {name} ({cls}) ---"
DISPLAY "HP: {hp}/{max_hp}"
DISPLAY "Attack: {atk} | Defense: {dfs}"
DISPLAY "Gold: {gold}"Refactor the main game menu into a game_loop() function. The function should contain a while loop with the options: 1. Fight (display a message), 2. Stats (call show_stats), 3. Inventory (call show_inventory), 4. Exit. The function does not receive parameters, it uses variables defined outside of it. Call it to start the game.
FUNCTION show_stats(...): ...
FUNCTION show_inventory(...): ...
FUNCTION game_loop():
WHILE True:
DISPLAY "--- MENU ---"
DISPLAY "1. Fight 2. Stats 3. Inventory 4. Exit"
READ choice
IF choice == "1":
DISPLAY "Searching for a monster..."
ELSE IF choice == "2":
show_stats(...)
ELSE IF choice == "3":
show_inventory(...)
ELSE IF choice == "4":
DISPLAY "Goodbye!"
BREAK loop
game_loop()Write 4 functions: add(a, b), subtract(a, b), multiply(a, b), and divide(a, b). Each returns the result of the operation. The divide function should check if b is 0 and return the message "Error: division by zero" instead of a result. Ask the user for two numbers and an operation (+, -, *, /) and call the corresponding function.
FUNCTION add(a, b): RETURN a + b
FUNCTION subtract(a, b): RETURN a - b
FUNCTION multiply(a, b): RETURN a * b
FUNCTION divide(a, b):
IF b == 0: RETURN "Error: division by zero"
RETURN a / b
READ a, b, operation
IF operation == "+": DISPLAY add(a, b)
...Write a function password_strength(password) that analyzes a password and returns a strength score (0-4): +1 if it has at least 6 characters, +1 if it has at least 10 characters, +1 if it contains at least one digit (search "0123456789" with find()), +1 if it contains at least one special character ("!@#$%"). Display the score and a message: 0-1 = "Weak", 2 = "Medium", 3 = "Good", 4 = "Excellent".
FUNCTION password_strength(password):
SET score = 0
IF length(password) >= 6: score += 1
IF length(password) >= 10: score += 1
SET digits = "0123456789"
SET has_digit = False
FOR character IN password:
IF digits.find(character) != -1:
has_digit = True
IF has_digit: score += 1
SET specials = "!@#$%"
SET has_special = False
FOR character IN password:
IF specials.find(character) != -1:
has_special = True
IF has_special: score += 1
RETURN score
READ password
SET score = password_strength(password)
DISPLAY message based on scoreYour game is now organized into clean functions! Each part of the game has its own function:
Check how well you understood the lesson with these 5 questions.