Victor Jeman Academy
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

In this lesson

  • Write your own functions with def, then call them by name to run them.
  • Pass values in through parameters so one function handles many cases.
  • Hand a result back to your code with return.
  • Stack small functions together so each one does a single job.

A function is a recipe you write down once and reuse forever. You give it a name, and from then on you cook with one line instead of rewriting the whole thing every time you get hungry. That is the entire idea, and it is about to save you from a game that has grown too big to read.

You have been using functions since lesson one without knowing it. print(), input(), len(), range(): someone else wrote those recipes, you just called them. Now you write your own.

The Python Kingdom code has grown across every lesson. By now it is a long wall of repeated if/elif and copy-pasted stat math. In this lesson you refactor the game into clean functions: one for hero creation, one for attack, one for inventory, one for the menu. Same game, a tenth of the chaos.

What are functions

A function is a block of code that does one specific thing and that you can reuse. You hand it some ingredients, it does the work, it hands you back a result.

Functions earn their keep three ways:

  • No more repetition. Write the stat math once, call it ten times. Fix a bug once, not in ten places.
  • The code reads itself. When you see calculate_pizza_price(), you know what it does without reading a single line inside.
  • Big problems shrink. You chop one scary problem into small functions, each handling one tiny job.

Your first function

Definitie vs Apel
definitie
def saluta_client():
  print("Bine ai venit!")
  print("Ce pizza doresti?")
apel
saluta_client()
output
...
apasa Ruleaza ca sa vezi cum functioneaza apelul

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. To call a function means to run it: you write its name followed by parentheses (). The parentheses are what actually triggers the work, which is why every print(...) you have written so far had them.

Result:

text
Welcome to Pizzeria Python!
What pizza would you like today?

You can call the function as many times as you want:

One catch: the function must be defined before you call it. Try to call greet_customer() above its def block and Python has no idea what you mean. You get a NameError. Recipe first, then cook.

Parameters

Cum ajung valorile in functie
Apelul
saluta_client("Andrei")
Functia
def saluta_client(nume):
print("Salut, " + nume + "!")
apasa "Apeleaza functia" ca sa vezi cum valorile ajung in parametri

Our greeting function works, but it is rigid. It says the same thing every time. What if you could tell it who to greet? That is the job of parameters.

Parameters are variables you place between the function parentheses. They get their values when you call the function:

Result:

text
Hello, Andrew!
Welcome to Pizzeria Python!
Hello, Maria!
Welcome to Pizzeria Python!

name gets "Andrew" in the first call and "Maria" in the second. Two words travel together here: the parameter is the blank in the recipe (name, written when you define the function), and the argument is the value you drop into that blank when you call it ("Andrew"). Same slot, two names depending on which side you are on.

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

print() vs return
rezultat = calculeaza(3, 5)
def calculeaza(a, b):
total = a + b
print(total)
def calculeaza(a, b):
total = a + b
return total
apasa "Ruleaza ambele" ca sa vezi diferenta

Our functions only printed things to the screen. But often you want a function to calculate something and hand the result back so the rest of your code can use it. That is return.

Keep these two apart in your head: print() shows text to a human. return hands a value back to the code that called the function, so the program can keep working 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

Functions get good when you stack them. Each one does a single thing, then they call each other like a chain. Here is a small pizza ordering system:

Result:

text
Order total: 47 dollars

Look at what calculate_total does not know: it has no idea how the base price or the toppings cost get calculated. It just calls the other two functions and adds up what they return. Each function owns one job and trusts the others to own theirs.

Default parameter values

Optional deep-dive: skip this section if you just want the basics. def, parameters, and return are the core of functions. Default and named arguments are a convenience you can pick up later.

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.

Look at the last call: order_pizza("small", drink="sprite"). When you name a parameter (drink="sprite"), you can skip the ones in between that already have defaults. These are named arguments, and they save you when a function has a long list of 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.

Eight values out of one function, eight variables to catch them on the way in. It works, but it is already getting awkward, and the menu function will have to pass all eight around again. Hold that thought. The next lesson packs all of a hero's stats into a single dictionary, so one value travels instead of eight.

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

Optional deep-dive: a meatier challenge that combines loops and string checks. Skip it if you just want the function basics.

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 (check each character with in "0123456789"), +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

Same game you wrote across lessons 4 to 7, now carved into functions. Each part of the game lives in its own block, and the menu just calls them:

There is still one ugly part you cannot miss: the hero's stats travel as eight loose variables (name, hp, max_hp, attack, defense, gold, potions...) that every function has to pass along by hand. That is the next problem to solve. In the next lesson you meet dictionaries, and the whole hero collapses into one tidy value you can hand around with a single name.

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?