Free

3: Building Our First Programs

⏱️ 40-55 minutes
📊 beginner

Chapter 9: "Functions: Useful Spells"

Professor Bit invited Alice to the kitchen, where he was going to make pizza.

— Today we'll talk about functions, — said the Professor, putting on an apron. — And making pizza will help us understand this concept.

— Functions? — Alice asked again. — Like in mathematics?

— In programming, functions are similar to mathematical ones, but they can do much more, — explained the Professor. — A function is a set of commands that perform a specific task. We give this set a name, and then we can call it whenever we need it.

The Professor pulled out a pizza recipe:
— Look, the entire pizza-making process can be broken down into separate tasks: knead dough, prepare sauce, grate cheese, add toppings, bake in the oven. Each such task we can format as a separate function.

He paused for a moment and quietly read:

Какая функция цветка?
Зачем ему цвести и пахнуть?
Чтоб, красоту увидев, ахнуть,
Коснувшись шёлка лепестка!

Какие функции лесов?
Они как будто прячут что-то,
Приберегают для кого-то
Под сенью вековых стволов.

Известных действий и шагов
Набор цикличных повторений,
План из намерений и мнений
Ты в функцию собрать готов.

Рецепт — как функции шаблон:
Едва подумаешь о блюде,
Как мысль твои нейроны будит,
Чтоб в точности свершился он.

Рождаясь с функцией такой:
Дышать, любить, расти, стремиться,
Чтоб уникально проявиться —
Собой рождается любой.

Byte displayed a code example on his screen:

python
def knead_dough():
print("1. Pour flour")
print("2. Add water")
print("3. Add salt and yeast")
print("4. Knead")
print("5. Let stand for 30 minutes")

def prepare_sauce():
print("1. Chop tomatoes")
print("2. Add spices")
print("3. Cook for 15 minutes")

def make_pizza():
knead_dough()
prepare_sauce()
print("Roll out dough")
print("Spread sauce")
print("Sprinkle cheese")
print("Add toppings")
print("Bake for 15 minutes at 220 degrees")
print("Pizza is ready!")

— You see, — said the Professor, starting to knead dough, — we created three functions. The first two perform separate steps, and the third uses them and adds its own actions.

In the kitchen: knead<em class=dough, preparesauce and make_pizza functions" class="rounded-lg shadow-md w-full h-auto" loading="lazy" decoding="async" />

— The keyword def means "define function", — he added. — After it comes the function name and parentheses. Parameters can be inside the parentheses, but we'll talk about that a bit later.

— Why are functions needed? — Alice asked, helping to grate cheese. — Why not just write all commands in order?

Logic, observing the process from the top shelf, replied:
— Functions solve several important tasks:

1. Code reuse — if you need to perform the same action multiple times, you can just call the function, not copy the code.
2. Program structuring — functions make code more organized and understandable.
3. Abstraction — you can call a function without thinking about how exactly it works inside.

— Like with a pizza recipe! — Alice guessed. — I can say "make pizza," and it's understandable even if I don't remember all the steps.

— Exactly! — the Professor was pleased. — And now let's talk about function parameters.

He wrote a new example:

python
def greet(name):
print("Hello, " + name + "!")

greet("Alice") # Will output: Hello, Alice!
greet("Byte") # Will output: Hello, Byte!

— Parameters are information we pass into a function, — the Professor explained. — In this example, the greet function takes a name parameter and uses it to create a greeting.

— Can we pass multiple parameters? — Alice asked.

— Of course! — the Professor nodded, getting ingredients for the sauce. — Here's an example of a function with multiple parameters:

python
def make_pizza(size, topping, cheese):
print("Making pizza of size", size)
print("Topping:", topping)
print("Cheese:", cheese)
# ... rest of preparation steps ...

make_pizza("large", "pepperoni", "mozzarella")
make_pizza("small", "mushrooms and olives", "cheddar")

— So we can make different pizzas with different parameters using the same function! — Alice exclaimed.

— Right! — the Professor confirmed. — And functions can also return a result using the return command.

python
def add(a, b):
sum = a + b
return sum

result = add(5, 3) # result will equal 8
print(result)

— Here the add function takes two numbers, adds them, and returns the result, — he explained. — This result can be saved in a variable or used immediately.

Byte demonstrated another example:

python
def calculate_cost(item, quantity):
if item == "apple":
price = 10
elif item == "banana":
price = 15
else:
price = 20

total = price * quantity
return total

sum = calculatecost("apple", 5) + calculatecost("banana", 3)
print("To pay:", sum, "rubles")

— Functions can be combined and call one another, — the Professor added, rolling out dough. — Like in the pizza recipe, where the makepizza function calls the kneaddough and prepare_sauce functions.

— Are there examples of functions in real life? — Alice asked.

— Many! — Logic replied. — Any repeating sequence of actions can be represented as a function. For example:

  • Morning routine: wash face, brush teeth, get dressed

  • Recipe in a cookbook

  • Furniture assembly instructions

  • Route to school
  • — Nature also has function analogs, — the Professor added. — For example, bees perform a certain "dance" to tell other bees where the nectar is. It's like a function with parameters: direction and distance to flowers.

    When the pizza was ready and sent to the oven, the Professor continued:
    — Functions are one way to organize code. They allow creating modular programs where each module is responsible for its task. This makes code more understandable, more reliable, and easier to change.

    — Like a LEGO constructor! — Alice guessed. — Each part plays its role, and together they create a complex model.

    — Great comparison! — the Professor praised. — And as in a constructor, you can create your own parts-functions to solve specific tasks.

    Task

    Imagine you're creating a "Forest Adventures" game. Write several functions that might be needed in such a game. For example:

    python
    def collectberries(berrytype, quantity):
    print("You collected", quantity, berry_type)
    return quantity * 5 # points for collecting berries

    def meet_animal(animal):
    if animal == "wolf":
    print("Careful! It's a wolf!")
    return "run away"
    elif animal == "rabbit":
    print("It's just a rabbit. It's harmless.")
    return "continue path"
    else:
    print("You met", animal)
    return "observe"

    Come up with 2-3 more functions for your game and describe what parameters they accept and what they return.