Functions
Functions are reusable blocks of code you define with def.
Syntax
def name(params):
return valueA 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.
Example
def greet(name):
return 'Hello, ' + name
message = greet('Ada')
print(message)
print(greet('Grace'))
# Output:
# Hello, Ada
# Hello, GraceWhen 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.
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.
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 (uses default exponent)
print(power(2, 10)) # 1024Function to reduce repeated logic
Encapsulates a discount formula in a function so the calculation is written once.
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