Python Functions Foundation
def / return Topic 07 Foundation

Functions — reusable blocks of logic

Foundation lesson for functions. Understand definition and call mechanics first, then see how functions model real workflows.

Picture this: a named machine

def names the machine. You pass inputs (arguments). It returns an output.

inputsarguments
→
def name(...)the machine
→
returnthe result

Call it many times. You write the body once.

In easy words: What is a function?

A function is a reusable block of code with a name. You call it whenever you need the same logic again.

Diagram — input → function → output

arguments def square(n): return value

Where functions are used

Used to organize code in every app: calculation helpers, API utilities, validation checks, and repeated workflows.

What is a function?

  • Define once with def name(params): — use as many times as needed.
  • Parameters are inputs; return value is the output.
  • Variables inside are local — they don't leak to the outside.
  • Default params (def greet(name="World")) make arguments optional.

Why use functions?

  • DRY — Don't Repeat Yourself. Write logic once, call it everywhere.
  • Decomposition — split a big problem into small named sub-tasks.
  • Testing — small functions are easier to verify and debug.

Real world: checkout calculator

An e-commerce site needs to compute tax, apply discount, and calculate the final price — on every product, for every user. Instead of repeating those 10 lines everywhere, developers write three functions: calc_tax(), apply_discount(), final_price(). Change the tax rate once and it's correct everywhere.

Function call machine — trace input → body → output

square(n) call trace

argument
?
→
body
n * n
→
return
?
Enter a number and click Call

Syntax reference

1def square(n):
2return n * n
3
4print(square(6)) # 36

Default parameters

1def greet(name="World"):
2print(f"Hello, {name}!")
3
4greet() # Hello, World!
5greet("Alice") # Hello, Alice!

Example Program

1def add(a, b):
2return a + b
3print(add(2, 3))

Functions — Topic Quiz

Check understanding

Answer all questions, then click Check answers. Use this before Practice in the editor.

Q1. What keyword defines a function?

Q2. What does return do?

Q3. Why write functions?

Q4. square(5) should return…

Score: —