1. Introduction
A function is a named, reusable block of code that performs a specific task. Functions let you break a large program into smaller, manageable pieces, avoid repeating code, and make programs easier to read, test, and debug. Python has built-in functions such as print() and len(), but you can also define your own using the def keyword.
Cricket analogy: A 'run drill' routine that a coach can call for any player breaks fielding training into a repeatable, focused task rather than re-explaining footwork from scratch every time, just like Python's built-in print() being ready to use alongside a coach's own custom drills.
Once defined, a function can be called any number of times with different inputs, which makes your code more modular and maintainable than writing the same logic repeatedly.
Cricket analogy: Once a fielding coach designs the 'high catch drill', it can be run with any player and any ball speed, session after session, without redesigning the drill each time a new recruit joins the academy.
2. Syntax
def function_name(parameter1, parameter2):
"""Optional docstring describing the function."""
# function body
result = parameter1 + parameter2
return result
3. Explanation
The def keyword starts a function definition, followed by the function name and a parenthesized list of parameters. The colon begins an indented code block that forms the function body. The optional return statement sends a value back to the caller and immediately exits the function; if a function reaches its end without a return statement, it implicitly returns None.
Cricket analogy: A coaching manual begins a drill with 'Drill:' followed by its name and a list of required equipment in parentheses; the colon marks where the step-by-step instructions begin, and an optional 'result' line at the end reports the outcome and immediately ends the drill — if no result line is given, the drill simply ends with no reported score.
A docstring, written as the first statement in the function body using triple quotes, documents what the function does and can be accessed later via function_name.__doc__ or the help() function.
Cricket analogy: A drill card's first line under the title, written in italics, explains what the drill trains and can be read later by any coach flipping through the manual's index or asking for the drill's description at a glance.
A function that only prints values and has no return statement still 'returns' something: Python automatically returns None. Beginners often mistakenly assume a function that prints its result has also returned that value to the caller.
4. Example
def greet(name):
"""Return a greeting message for the given name."""
message = f"Hello, {name}! Welcome to Python."
return message
def log_greet(name):
print(f"Logging: greeting {name}")
# no return statement
result1 = greet("Asha")
print(result1)
result2 = log_greet("Ravi")
print(result2)
print(greet.__doc__)
5. Output
Hello, Asha! Welcome to Python.
Logging: greeting Ravi
None
Return a greeting message for the given name.
6. Key Takeaways
- Functions are defined with the def keyword and can accept parameters and return values.
- A function without an explicit return statement implicitly returns None.
- Docstrings document a function's purpose and are accessible via __doc__.
- Calling a function executes its body top to bottom until a return statement or the end of the block.
- Functions promote code reuse, readability, and easier testing/debugging.
Practice what you learned
1. What value does a Python function return if it has no return statement?
2. Which keyword is used to define a function in Python?
3. How can you access a function's docstring after it is defined?
4. What happens to code written after a return statement inside the same code branch?
5. In the Example, what does print(result2) output after calling log_greet('Ravi')?
6. Which of these is a valid reason to use functions?
Was this page helpful?
You May Also Like
Function Arguments in Python
Understanding positional, positional-only, keyword-only, *args, and **kwargs arguments in Python function signatures.
Default and Keyword Arguments in Python
How to give function parameters default values and call functions with keyword arguments, plus the notorious mutable default argument trap.
Lambda Functions in Python
Writing small anonymous functions with lambda, using them with map/filter/sorted, and avoiding the late-binding closure trap in loops.
Recursion in Python
Writing recursive functions with proper base cases, understanding the call stack, and avoiding RecursionError from missing base cases or excessive depth.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics