Functions

Functions are reusable blocks of code you define with def.

Syntaxdef name(params): return value

A function is a reusable block of code. You define it once with the def keyword and call it whenever you need it.

Parameters and arguments

Parameters are the named inputs in the definition. The values you pass when calling are the arguments.

How a function call passes arguments in and returns a value outdef add(a, b):return a + badd(3, 4)arguments inreturn out7
Arguments flow into the function; the return statement sends a value back out.

Example

Example · python
def greet(name):
    return 'Hello, ' + name

message = greet('Ada')
print(message)
print(greet('Grace'))

# Output:
# Hello, Ada
# Hello, Grace

When to use it

  • A web app extracts repeated email validation logic into a function called once per form field.
  • A data pipeline defines a clean_text() function applied to every row in a CSV.
  • A game separates the score calculation into its own function so it can be unit-tested independently.

More examples

Define and call a function

Defines a simple function with one parameter and calls it twice with different arguments.

Example · python
def greet(name):
    print(f'Hello, {name}!')

greet('Alice')
greet('Bob')

# Output:
# Hello, Alice!
# Hello, Bob!

Function with a default parameter

Uses a default parameter so callers can omit 'exponent' to square or supply their own.

Example · python
def power(base, exponent=2):
    return base ** exponent

print(power(5))     # 25 (uses default exponent)
print(power(2, 10)) # 1024

Function to reduce repeated logic

Encapsulates a discount formula in a function so the calculation is written once.

Example · python
def apply_discount(price, pct):
    return round(price * (1 - pct / 100), 2)

print(apply_discount(100, 10))   # 90.0
print(apply_discount(49.99, 25)) # 37.49

Discussion

  • Be the first to comment on this lesson.