Victor Jeman - Frontend Architectv3.0
Python Fundamentals14 min

Build your own functions

Learn to create your own functions with parameters and return values to organize your code.

What You'll Learn

  • Define and call your own functions using def
  • Pass information to functions through parameters
  • Return results from functions with return
  • Combine multiple functions to solve complex problems

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.

What are functions

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:

  • You avoid repetition. Instead of writing the same code 10 times, you put it in a function and call it 10 times.
  • Your code becomes clearer. When you read calculate_pizza_price(), you immediately know what that piece of code does, even without seeing the details.
  • You solve big problems in small steps. You can break a complicated problem into small functions, each one handling a single task.

Your first function

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:

text
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.

Parameters

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:

text
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:

text
Your order: large pizza
Crust type: thin
Your order: medium pizza
Crust type: fluffy

The order matters: the first argument you pass goes to the first parameter, the second to the second, and so on.

Functions with return

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:

text
The price of your pizza is: 36 dollars

Without 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:

Combining functions

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:

text
Order total: 47 dollars

Notice 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.

Default parameter values

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:

text
Pizza large with thin crust
Drink: fanta
Pizza medium with regular crust
Drink: cola
Pizza small with regular crust
Drink: sprite

The 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.

Exercise : Hero creation function

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.

Exercise : Attack function

Write 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.

Exercise : Inventory and stats functions

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.

Exercise : Game menu as function

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.

Exercise : Calculator with functions

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.

Exercise : Password strength checker

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".

Complete game code: Python Kingdom (Lesson 8)

Your game is now organized into clean functions! Each part of the game has its own function:

Test Your Knowledge

Check how well you understood the lesson with these 5 questions.

Question 1 of 5

What keyword do we use to define a function in Python?