Python Tutorial · Functions · Lesson 23 of 42
Python Functions
Define functions with def, return values and write docstrings.
Defining a function
A function is a reusable block of code. Define it with def, give it parameters, and return a result.
def greet(name):
"""Return a friendly greeting."""
return f"Hello, {name}!"
message = greet("Ada")
print(message)
def log(text):
print("LOG:", text)
result = log("started")
print(result)
Output
Hello, Ada! LOG: started None
A function without return returns None.
Why functions?
- Reuse: write logic once, call it many times.
- Naming: a good function name explains what the code does.
- Testing: small functions are easy to test.
Functions are objects
You can store functions in variables, pass them to other functions and return them — this is what makes decorators and callbacks possible.
def shout(text):
return text.upper() + "!"
def apply(func, value):
return func(value)
print(apply(shout, "hi"))
print(apply(len, "hello"))
Output
HI! 5
Test yourself
What does a function return if it has no return statement?
0None""False
Show answer
Answer: None