Defining Functions
Functions are the building blocks of reusable code. They let you define a block of code once and use it anywhere in your program by simply calling its name. Functions make your code more organized, readable, and maintainable - they're essential for writing professional Python code!
Defining Functions
In Python, you define a function using the def keyword, followed by the function
name, parentheses for parameters, and a colon. The function body is indented below. Good
function names use snake_case and start with a verb describing what the function does.
Click Run to execute your code
def. A method is a function that belongs to an object and is called with dot
notation like list.append(). Under the hood, methods are just functions that
receive the object as their first argument (self).
Calling Functions
To execute a function, you call it by writing its name followed by parentheses. The parentheses are crucial - without them, you're referring to the function object itself, not executing it. You can pass arguments, store return values, and chain function calls.
Click Run to execute your code
func(1, 2, c=3) is valid,
but func(a=1, 2, 3) is a syntax error. Keyword arguments make calls more
readable and allow you to skip optional parameters.
Docstrings: Documenting Functions
A docstring is a string literal that appears as the first statement in a function.
It documents what the function does, its parameters, and return value. Python's built-in
help() function and IDEs use docstrings to provide documentation.
Click Run to execute your code
#) are for
implementation notes and are not accessible at runtime. Docstrings ("""...""")
are stored in the function's __doc__ attribute and can be accessed
programmatically. Always use docstrings for function documentation, not comments.
Practical Function Examples
Let's look at some real-world function examples - utility functions for temperature conversion, string processing, validation, and working with lists. These patterns will appear constantly in your Python programs.
Click Run to execute your code
Common Mistakes
1. Forgetting parentheses when calling
# Wrong - this is the function object, not a call
result = my_function # No execution!
print(result) # Prints:
# Correct - use parentheses to call
result = my_function()
print(result) # Prints the actual return value
2. Missing colon after function definition
# Wrong - missing colon
def greet(name) # SyntaxError!
print(f"Hello, {name}")
# Correct - include the colon
def greet(name):
print(f"Hello, {name}")
3. Incorrect indentation in function body
# Wrong - inconsistent indentation
def calculate(a, b):
result = a + b
extra = result * 2 # IndentationError!
return extra
# Correct - consistent indentation
def calculate(a, b):
result = a + b
extra = result * 2
return extra
4. Calling function before definition
# Wrong - function called before it's defined
result = add(3, 5) # NameError: name 'add' is not defined
def add(a, b):
return a + b
# Correct - define first, then call
def add(a, b):
return a + b
result = add(3, 5)
5. Using wrong number of arguments
def greet(first_name, last_name):
print(f"Hello, {first_name} {last_name}")
# Wrong - too few arguments
greet("Alice") # TypeError: missing 1 required positional argument
# Wrong - too many arguments
greet("Alice", "Smith", "Ms.") # TypeError: takes 2 positional arguments but 3 were given
# Correct - exact number of arguments
greet("Alice", "Smith")
Exercise: Calculator Functions
Task: Create basic calculator functions.
Requirements:
- Define
add(a, b)- returns sum - Define
subtract(a, b)- returns difference - Define
multiply(a, b)- returns product - Each function should have a docstring
- Test each function with sample values
Click Run to execute your code
Show Solution
def add(a, b):
"""Return the sum of a and b."""
return a + b
def subtract(a, b):
"""Return a minus b."""
return a - b
def multiply(a, b):
"""Return the product of a and b."""
return a * b
# Test the functions
print(f"5 + 3 = {add(5, 3)}")
print(f"10 - 4 = {subtract(10, 4)}")
print(f"6 * 7 = {multiply(6, 7)}")
Summary
- Define:
def function_name(parameters): - Call:
function_name(arguments) - Naming: Use
snake_casewith descriptive verbs - Docstrings: First line in function body:
"""Description.""" - Parameters: Variables in definition; arguments are values passed when calling
- Execution order: Define before calling; Python reads top-to-bottom
- Parentheses: Always use
()to call; without them you get the function object
What's Next?
Now that you can define and call functions, let's dive deeper into Function
Arguments - you'll learn about default values, keyword arguments, and how to
create flexible functions that accept any number of arguments with *args
and **kwargs!
Enjoying these tutorials?