Functions: повторное использование code

Возвращаемся к Python.
В предыдущем уроке ты изучил dictionaries.
Твои программы научились хранить structured data через keys и values.
Ты писал что-то такое:
user = {
"name": "Anna",
"age": 25,
"city": "Rome"
}
Очень хорошо.
Теперь твои программы могут хранить meaningful data.
Не просто случайные values, которые летают как confused balloons.
Но теперь у нас другая проблема.
Что делать, если нужно использовать один и тот же code много раз?
Например:
print("Hello, Anna!")
print("Welcome to the program.")
print("Have a nice day!")
Потом позже:
print("Hello, Marco!")
print("Welcome to the program.")
print("Have a nice day!")
Потом ещё раз:
print("Hello, Sofia!")
print("Welcome to the program.")
print("Have a nice day!")
Это работает.
Но это repetition.
А repeated code опасен.
Потому что однажды нужно что-то изменить.
Потом нужно изменить это в пяти местах.
Потом ты забываешь одно место.
Потом появляется bug.
Потом coffee становится emergency fuel.
Functions решают эту проблему.
Functions позволяют reuse code.
Ты пишешь code один раз.
Потом вызываешь его каждый раз, когда он нужен.
Очень полезно.
Очень clean.
Очень Python.
Что ты изучишь
В этом уроке ты изучишь:
- что такое function;
- почему functions полезны;
- как создать function через
def; - как вызвать function;
- как работает indentation в functions;
- как использовать parameters;
- как передавать arguments;
- как возвращать values через
return; - разницу между
print()иreturn; - как использовать default parameter values;
- как работает variable scope;
- как избегать repeated code;
- типичные ошибки начинающих;
- как строить маленькие programs с functions.
К концу этого урока твой code станет более organized.
Меньше repetition.
Больше structure.
Меньше copy-paste disasters.
Надеемся.
Functions — это один из самых больших шагов в programming.
До functions code — это длинная дорога.
После functions code становится городом со signs.
Всё ещё можно заблудиться.
Но хотя бы теперь есть signs.
Что такое function?
Function — это reusable block of code.
Ты define её один раз.
Потом можешь использовать много раз.
Пример:
def say_hello():
print("Hello!")
Это создаёт function called:
say_hello
Но создание function не запускает её.
Чтобы запустить function, нужно её вызвать:
say_hello()
Полный пример:
def say_hello():
print("Hello!")
say_hello()
Output:
Hello!
Function — это как маленькая машина.
Ты строишь её один раз.
Потом нажимаешь button.
Button — это function call.
Очень technical.
Очень button.
Твоя первая function
Создай файл:
functions.py
Напиши:
def greet():
print("Hello from a function!")
greet()
Запусти:
python functions.py
или:
python3 functions.py
Output:
Hello from a function!
Эта строка создаёт function:
def greet():
Эта строка принадлежит function:
print("Hello from a function!")
Эта строка вызывает function:
greet()
Важно:
def создаёт function.
Calling the function запускает её.
Если ты только define function, но никогда её не call, ничего не произойдёт.
Python вежливый.
Он не запускает functions, если ты не попросишь.
В отличие от некоторых людей, которые дают advice без запроса.
Syntax function
Basic function выглядит так:
def function_name():
code_here
Пример:
def show_menu():
print("1. Add item")
print("2. Show items")
print("q. Quit")
Parts:
def начинает function definition
function_name название function
() parentheses
: начинает function body
indentation code внутри function
Colon важен.
Indentation важна.
Python всё ещё очень сильно любит indentation.
Очень.
Python видит indentation как building plan.
Если indentation неправильная, building collapses.
Digitally.
Вызов function много раз
Functions можно вызывать много раз.
Пример:
def say_hello():
print("Hello!")
say_hello()
say_hello()
say_hello()
Output:
Hello!
Hello!
Hello!
Function была написана один раз.
Но запустилась три раза.
Это сила functions.
Никакого copy-paste одного и того же code повсюду.
Ты создаёшь один reusable block.
Потом используешь его, когда нужно.
Очень clean.
Очень цивилизованно.
Очень не как папка final_final_REAL_final.py.
Почему functions полезны
Functions помогают:
- избегать repetition;
- organize code;
- reuse logic;
- делать code easier to read;
- делать code easier to change;
- разбивать big problems на smaller problems.
Без functions program может стать одной длинной рекой code.
Страшной рекой.
С functions ты можешь разделить program на smaller parts.
Пример:
show menu
get user choice
add task
show tasks
quit program
Каждая часть может стать function.
Это делает code easier to understand.
Твой future self скажет тебе спасибо.
Возможно.
Future self часто tired.
Indentation в functions
Code внутри function должен быть indented.
Правильно:
def greet():
print("Hello!")
Неправильно:
def greet():
print("Hello!")
Python покажет:
IndentationError
Indented lines принадлежат function.
Пример:
def greet():
print("Hello!")
print("Welcome!")
print("This is outside the function.")
Здесь:
print("Hello!")
print("Welcome!")
принадлежат function.
Эта строка:
print("This is outside the function.")
не принадлежит function.
Indentation решает ownership.
Как documents.
Но со spaces.
Function names
Function names должны быть clear.
Хорошо:
def show_menu():
print("Menu")
Хорошо:
def calculate_total():
print("Calculating...")
Плохо:
def x():
print("Something")
Плохо:
def do_stuff():
print("Stuff")
Используй names, которые объясняют, что function делает.
Function names обычно используют lowercase letters и underscores:
show_menu
calculate_total
add_product
get_user_name
Этот style называется snake_case.
Python любит snake_case.
Не настоящих snakes.
Наверное.
Parameters
Parameter позволяет function получать data.
Пример:
def greet_user(name):
print(f"Hello, {name}!")
Здесь:
name
это parameter.
Это как input variable для function.
Теперь вызови function:
greet_user("Anna")
greet_user("Marco")
greet_user("Sofia")
Полный пример:
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Anna")
greet_user("Marco")
greet_user("Sofia")
Output:
Hello, Anna!
Hello, Marco!
Hello, Sofia!
Function reusable.
Message меняется в зависимости от value, который ты передаёшь.
Очень полезно.
Очень clean.
Очень less copy-paste.
Arguments
Когда ты вызываешь function, value, который ты передаёшь, называется argument.
Пример:
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Anna")
Здесь:
name
это parameter.
А:
"Anna"
это argument.
Простое объяснение:
parameter = variable в function definition
argument = actual value, переданный во время function call
Люди часто используют эти слова немного свободно.
Не паникуй.
Главная идея:
Functions могут получать values.
Вот это самое важное.
Function с двумя parameters
Function может иметь больше одного parameter.
Пример:
def greet_user(name, city):
print(f"Hello, {name} from {city}!")
Вызови её:
greet_user("Anna", "Rome")
Полный пример:
def greet_user(name, city):
print(f"Hello, {name} from {city}!")
greet_user("Anna", "Rome")
greet_user("Marco", "Milan")
Output:
Hello, Anna from Rome!
Hello, Marco from Milan!
Order matters.
Это:
greet_user("Anna", "Rome")
означает:
name = Anna
city = Rome
Если поменять местами:
greet_user("Rome", "Anna")
Output:
Hello, Rome from Anna!
Technically correct.
Emotionally strange.
Functions и calculations
Functions отлично подходят для calculations.
Пример:
def add_numbers(a, b):
total = a + b
print(total)
add_numbers(5, 3)
Output:
8
Здесь:
a
b
это parameters.
Эта function добавляет их и prints result.
Другой пример:
def calculate_total(price, quantity):
total = price * quantity
print(f"Total: {total:.2f}")
calculate_total(10.00, 3)
Output:
Total: 30.00
Это полезно.
Но есть лучший способ.
Вместо того, чтобы только print result, мы можем return it.
И тут приходит return.
Очень важно.
Очень function.
Returning values
Function может return value.
Пример:
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result)
Output:
8
Function:
def add_numbers(a, b):
return a + b
не prints.
Она gives result back.
Эта строка сохраняет result:
result = add_numbers(5, 3)
Потом мы print it:
print(result)
Это очень важно.
Function, которая returns value, более flexible.
Ты можешь print value.
Или save it.
Или use it in another calculation.
Или pass it to another function.
Вот здесь functions становятся powerful.
print() vs return
Это очень важно.
print() показывает что-то на screen.
return отправляет value назад из function.
Пример с print():
def add_numbers(a, b):
print(a + b)
result = add_numbers(5, 3)
print(result)
Output:
8
None
Почему None?
Потому что function printed result, но не returned anything.
Теперь пример с return:
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result)
Output:
8
Простое правило:
Use print() to show something.
Use return to give a value back.
Это один из самых важных beginner lessons.
Очень важно.
Очень легко перепутать.
Очень нормально.
Function, которая returns total
Пример:
def calculate_total(price, quantity):
return price * quantity
total = calculate_total(25.00, 4)
print(f"Total: {total:.2f}")
Output:
Total: 100.00
Теперь function calculates.
Main program решает, что делать с result.
Это cleaner.
Function имеет одну job:
calculate total
Main program имеет другую job:
show result
Это separation.
Очень хорошо.
Очень professional.
Очень “сегодня без spaghetti”.
Default parameter values
Parameter может иметь default value.
Пример:
def greet_user(name="Guest"):
print(f"Hello, {name}!")
Теперь можно вызвать:
greet_user("Anna")
greet_user()
Полный пример:
def greet_user(name="Guest"):
print(f"Hello, {name}!")
greet_user("Anna")
greet_user()
Output:
Hello, Anna!
Hello, Guest!
Когда ты передаёшь name, Python использует его.
Когда ты не передаёшь name, Python использует "Guest".
Это полезно, когда value optional.
Default values — это как backup plans.
Редкая вещь в programming, которая звучит comforting.
Keyword arguments
Можно передавать arguments by name.
Пример:
def describe_product(name, price):
print(f"{name}: {price:.2f}")
describe_product(name="Keyboard", price=70.00)
Output:
Keyboard: 70.00
Это называется keyword arguments.
Это может делать function calls clearer.
Особенно когда parameters много.
Пример:
def create_user(name, age, city):
print(f"{name}, {age}, {city}")
create_user(name="Anna", age=25, city="Rome")
Это readable больше, чем:
create_user("Anna", 25, "Rome")
Оба варианта работают.
Keyword arguments делают meaning clearer.
А clear code менее вероятно нападёт на тебя позже.
Обычно.
Variable scope
Variables, созданные внутри function, существуют только внутри этой function.
Пример:
def greet():
message = "Hello!"
greet()
print(message)
Это даёт error:
NameError
Почему?
Потому что message была создана внутри function.
Outside function она не существует.
Это называется scope.
Scope означает:
where a variable is available
Variable внутри function — local to that function.
Она живёт там.
Она не выходит наружу.
Очень private.
Очень introverted.
Local variables
Пример:
def calculate_total(price, quantity):
total = price * quantity
return total
result = calculate_total(10, 3)
print(result)
Output:
30
Здесь:
total
существует внутри function.
Это работает:
return total
потому что мы inside function.
Но это не работало бы:
print(total)
outside function.
Variable total local.
Если result нужен outside function, return it.
Это correct way.
Не пытайся красть local variables через window.
Python locks the window.
Function с list
Functions могут receive lists.
Пример:
def show_products(products):
for product in products:
print(f"- {product}")
items = ["Keyboard", "Mouse", "Notebook"]
show_products(items)
Output:
- Keyboard
- Mouse
- Notebook
Function получает list.
Потом проходит по list.
Это очень распространено.
Functions и lists отлично работают вместе.
List хранит many values.
Function processes them.
Очень полезно.
Очень реально.
Очень “это потом может стать report”.
Function, которая calculates list total
Пример:
def calculate_total(prices):
total = 0
for price in prices:
total += price
return total
prices = [10.00, 25.50, 5.00]
total = calculate_total(prices)
print(f"Total: {total:.2f}")
Output:
Total: 40.50
Эта function работает с любым list of prices.
Пример:
order_one = [10.00, 20.00]
order_two = [5.50, 7.25, 100.00]
print(calculate_total(order_one))
print(calculate_total(order_two))
Та же function работает с different data.
Это beauty of functions.
Write once.
Reuse.
Feel slightly powerful.
Function с dictionary
Functions могут receive dictionaries тоже.
Пример:
def show_user(user):
print(f"Name: {user['name']}")
print(f"Age: {user['age']}")
print(f"City: {user['city']}")
user = {
"name": "Anna",
"age": 25,
"city": "Rome"
}
show_user(user)
Output:
Name: Anna
Age: 25
City: Rome
Это очень полезно.
Dictionary хранит structured data.
Function displays или processes it.
Real applications делают это постоянно.
Users.
Products.
Orders.
Profiles.
Everything становится easier, когда functions handle structured data.
Очень practical.
Очень backend-friendly.
Function с list of dictionaries
Пример:
def show_products(products):
for product in products:
print(f"{product['name']}: {product['price']:.2f}")
products = [
{"name": "Keyboard", "price": 70.00},
{"name": "Mouse", "price": 25.00},
{"name": "Notebook", "price": 5.50}
]
show_products(products)
Output:
Keyboard: 70.00
Mouse: 25.00
Notebook: 5.50
Это strong pattern.
Ты уже знаешь lists.
Ты уже знаешь dictionaries.
Теперь ты ставишь functions вокруг них.
Так programs становятся organized.
Data structures store data.
Functions work with data.
Очень важная idea.
Очень software.
Типичная ошибка: забыть parentheses
Неправильно:
def greet():
print("Hello!")
greet
Это не calls function.
Правильно:
greet()
Parentheses call the function.
Без parentheses ты просто refers to function.
Python говорит:
Да, эта function существует.
Но не запускает её.
Function call требует parentheses.
Tiny circles.
Big responsibility.
Типичная ошибка: забыть colon
Неправильно:
def greet()
print("Hello!")
Правильно:
def greet():
print("Hello!")
Function definitions требуют colon.
Python любит colons.
Conditions need colons.
Loops need colons.
Functions need colons.
Python basically building a small colon collection.
Respect it.
Типичная ошибка: неправильная indentation
Неправильно:
def greet():
print("Hello!")
Правильно:
def greet():
print("Hello!")
Function body должен быть indented.
Если indentation неправильная, Python даёт:
IndentationError
Это не Python being dramatic.
Он реально не знает, что belongs to function.
Indentation is structure.
Again.
Always again.
Типичная ошибка: забыть return
Неправильно:
def add_numbers(a, b):
total = a + b
result = add_numbers(5, 3)
print(result)
Output:
None
Почему?
Потому что function ничего не returns.
Правильно:
def add_numbers(a, b):
total = a + b
return total
result = add_numbers(5, 3)
print(result)
Output:
8
Если тебе нужен value outside function, return it.
Не просто calculate it.
Calculation trapped inside function — как pizza behind glass.
Looks nice.
Not useful.
Типичная ошибка: code после return
Когда Python доходит до return, function stops.
Пример:
def test():
return "Done"
print("This will not run")
message = test()
print(message)
Output:
Done
Эта строка не выполнится:
print("This will not run")
Потому что она after return.
return exits function immediately.
Очень важно.
Anything after return in the same block is ignored.
Как advice после того, как кто-то уже закрыл door.
Типичная ошибка: too many responsibilities
Bad function:
def do_everything():
print("Show menu")
print("Ask user")
print("Add product")
print("Calculate total")
print("Send email")
Эта function делает too much.
Лучше:
def show_menu():
print("Menu")
def add_product():
print("Add product")
def calculate_total():
print("Calculate total")
Good function обычно делает one clear thing.
Не всегда perfect.
Но try.
Functions должны быть small enough to understand.
Если function становится huge, возможно, её нужно split.
Как pizza.
Но с code.
Мини-программа: greeting function
Создай файл:
greeting_function.py
Напиши:
def greet_user(name):
print(f"Hello, {name}!")
print("Welcome to the program.")
user_name = input("What is your name? ")
greet_user(user_name)
Пример:
What is your name? Anna
Output:
Hello, Anna!
Welcome to the program.
Эта программа использует:
- function definition;
- parameter;
- user input;
- function call.
Просто.
Но важно.
Ты уже не просто пишешь linear code.
Ты organize behavior.
Очень хорошо.
Мини-программа: total calculator
Создай файл:
total_calculator.py
Напиши:
def calculate_total(price, quantity):
return price * quantity
price = float(input("Price: "))
quantity = int(input("Quantity: "))
total = calculate_total(price, quantity)
print(f"Total: {total:.2f}")
Пример:
Price: 25
Quantity: 4
Output:
Total: 100.00
Эта программа использует:
- function with parameters;
return;- input;
- type conversion;
- formatted output.
Очень practical.
Очень shop-like.
Очень “это однажды может стать invoice”.
Осторожно.
Invoices attract taxes.
Мини-программа: average function
Создай файл:
average_function.py
Напиши:
def calculate_average(numbers):
total = 0
for number in numbers:
total += number
return total / len(numbers)
scores = []
score_count = int(input("How many scores? "))
for number in range(1, score_count + 1):
score = float(input(f"Score {number}: "))
scores.append(score)
average = calculate_average(scores)
print(f"Average: {average:.2f}")
Пример:
How many scores? 3
Score 1: 80
Score 2: 90
Score 3: 70
Output:
Average: 80.00
Эта программа объединяет:
- lists;
- loops;
- functions;
- input;
return;- calculations.
Очень strong beginner practice.
Это real pattern.
Collect data.
Pass data to a function.
Get result.
Show result.
Clean.
Useful.
Professional enough to scare spaghetti code away.
Практика
Создай файл:
practice_functions.py
Напиши программу, которая:
- defines function called
calculate_discount; - receives
priceиdiscount_percent; - returns discounted price;
- asks user for price and discount;
- prints final price.
Пример решения:
def calculate_discount(price, discount_percent):
discount_amount = price * discount_percent / 100
final_price = price - discount_amount
return final_price
price = float(input("Price: "))
discount = float(input("Discount percent: "))
final_price = calculate_discount(price, discount)
print(f"Final price: {final_price:.2f}")
Пример:
Price: 100
Discount percent: 20
Output:
Final price: 80.00
Это очень полезно.
Discounts повсюду.
Shops используют их.
Customers любят их.
Developers calculate them.
Accountants verify them.
Everyone has a role.
Very organized chaos.
Мини-задание
Создай файл:
task_manager_functions.py
Твоя программа должна:
- начать с empty list called
tasks; - define function called
show_menu; - define function called
add_task; - define function called
show_tasks; - use
while Trueloop; - allow user to add tasks;
- allow user to show tasks;
- allow user to quit.
Пример решения:
tasks = []
def show_menu():
print("----- Task Manager -----")
print("1. Add task")
print("2. Show tasks")
print("q. Quit")
def add_task(tasks):
task = input("Task: ")
tasks.append(task)
print("Task added.")
def show_tasks(tasks):
if len(tasks) == 0:
print("No tasks yet.")
else:
print("Tasks:")
for task in tasks:
print(f"- {task}")
while True:
show_menu()
choice = input("Choose an option: ").lower()
if choice == "1":
add_task(tasks)
elif choice == "2":
show_tasks(tasks)
elif choice == "q":
print("Goodbye.")
break
else:
print("Unknown option.")
Это лучшая версия task manager.
Почему?
Потому что code organized into functions.
Каждая function имеет job:
show_menu shows the menu
add_task adds a task
show_tasks shows all tasks
Main loop становится easier to read.
В этом и смысл functions.
Они делают programs easier to organize.
Less chaos.
More structure.
Still Python.
Extra challenge: product functions
Создай файл:
product_functions.py
Построй program с этими functions:
create_product()
show_product(product)
calculate_total(products)
Каждый product должен быть dictionary с:
name
price
quantity
Пример идеи:
def create_product():
product = {
"name": input("Name: "),
"price": float(input("Price: ")),
"quantity": int(input("Quantity: "))
}
return product
def show_product(product):
total = product["price"] * product["quantity"]
print(f"{product['name']}: {product['quantity']} x {product['price']:.2f} = {total:.2f}")
def calculate_total(products):
total = 0
for product in products:
total += product["price"] * product["quantity"]
return total
products = []
product_count = int(input("How many products? "))
for number in range(1, product_count + 1):
print(f"Product {number}")
product = create_product()
products.append(product)
print("----- Products -----")
for product in products:
show_product(product)
total = calculate_total(products)
print(f"Total: {total:.2f}")
Этот challenge объединяет:
- functions;
- lists;
- dictionaries;
- loops;
- input;
- return values;
- calculations.
Это serious beginner Python.
Small shop logic.
Structured data.
Reusable code.
Очень strong.
Очень useful.
Очень “ты начинаешь build real things”.
Checklist для начинающих
Когда твоя function не работает, проверь:
Я использовал def?
Я добавил parentheses?
Я добавил colon?
Я сделал indentation для function body?
Я call function?
Я передал correct number of arguments?
Я написал function name правильно?
Я использовал return, если мне нужен value back?
Я не путаю print() и return?
Variable local to the function?
Я поставил code after return?
Function does too many things?
Functions powerful.
Но они добавляют new mistakes.
Это нормально.
Сначала functions кажутся extra work.
Потом однажды ты пишешь program без functions и чувствуешь pain.
Вот тогда ты понимаешь.
Growth is beautiful.
And slightly annoying.
Итог
Сегодня ты изучил:
- functions — это reusable blocks of code;
defсоздаёт function;- calling a function runs it;
- function bodies должны быть indented;
- parameters позволяют functions receive data;
- arguments — это values passed to functions;
- functions могут иметь multiple parameters;
returnsends value back;print()shows value, but does not return it;- default parameter values possible;
- keyword arguments могут сделать calls clearer;
- variables inside functions are local;
- functions могут receive lists;
- functions могут receive dictionaries;
- functions могут work with lists of dictionaries;
- good functions usually do one clear job;
- functions помогают organize programs и reduce repetition.
Это огромный шаг.
Твой code теперь может стать cleaner.
More reusable.
More organized.
Less copy-paste.
Less chaos.
Functions — один из main tools, которые превращают beginner scripts в real programs.
Ты уже не просто пишешь commands.
Ты создаёшь reusable behavior.
Это serious progress.
Очень Python.
Очень next level.
Следующий урок
В следующем уроке мы изучим files.
Files позволяют твоим programs save data.
Сейчас, когда program ends, data disappears.
Очень sad.
Очень temporary.
С files можно write data to disk и read it later.
Например:
save tasks
load tasks
save contacts
read notes
write reports
Это очень важно.
Потому что programs становятся намного useful, когда они remember things.
Memory is power.
Unless you saved the wrong file.
Then memory is drama.
Very educational drama.