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.