Function Definition and Call: How to Create Your First Function in Python?

Why Functions?

In programming, a function is like a “code toolkit.” If you need to repeat a block of code (e.g., printing a greeting or calculating the sum of two numbers), writing the same code repeatedly makes your program long and hard to maintain. Functions let you “package” this code, give it a name, and then call that name to execute it later—saving time and ensuring code consistency.

Basic Syntax of Functions

Defining functions in Python is straightforward, using the def keyword. The syntax is:

def function_name(parameter1, parameter2, ...):
    """Function description (optional but recommended)"""
    # Function body: specific code to execute (must be indented)
    statement1
    statement2
    # Return result (optional)
    return result
  • def: Mandatory keyword to define a function.
  • Function Name: Custom name following variable naming rules (letters, numbers, underscores; cannot start with a number or use Python keywords like if/for).
  • Parameters: Variables in parentheses (e.g., name, a, b) to receive external data. Leave parentheses empty if no parameters are needed.
  • Function Body: Code block after the colon, must be indented (typically 4 spaces). This is how Python distinguishes code blocks.
  • return: Returns the function’s result (if omitted, returns None by default).

Defining Your First Function

Example 1: “No Parameters, No Return Value”

Define a function to print a greeting:

# Define the function
def say_hello():
    # Function body (4-space indentation)
    print("Hello, Python!")
    print("This is my first function~")

Call the function: Use the function name followed by parentheses (even with no parameters):

# Call the function
say_hello()

Output:

Hello, Python!
This is my first function~

Example 2: Function with Parameters and Return Value

Define a function to calculate the sum of two numbers:

# Define function with parameters a and b
def add_numbers(a, b):
    result = a + b  # Calculate the sum
    return result   # Return the result

Call the function: Pass two parameters (positionally):

# Call the function and store the return value
sum_result = add_numbers(3, 5)
print("3 + 5 =", sum_result)  # Output: 3 + 5 = 8

Key Points About Function Calls

  1. Parameter Passing: Parameters must be passed in the defined order (positional arguments) or explicitly by name (keyword arguments).
   def greet(name, message):
       print(f"{message}, {name}!")

   greet("Alice", "Good morning")  # Positional arguments
   greet(message="Good evening", name="Bob")  # Keyword arguments (order can be swapped)
  1. Return Value Handling: The return value must be stored in a variable to be used later.
   def multiply(x, y):
       return x * y

   product = multiply(4, 5)  # Must assign to a variable to use the result
   print(product)  # Output: 20
  1. No Return Value: If a function has no return, calling it will not produce a result, but the function body still executes.
   def print_hi():
       print("Hi there!")

   result = print_hi()  # No return value; result = None
   print(result)  # Output: None

Common Issues & Precautions

  1. Indentation Error: The function body must be indented. Missing indentation causes an error.
   def add(a, b):
   print(a + b)  # Error! Indentation missing → IndentationError
  1. Duplicate Function Names: Redefining a function overwrites the previous one. Ensure unique naming.

  2. Mismatched Parameters: The number of arguments during a call must match the definition (unless using default parameters).

   def greet(name):
       print(f"Hello, {name}")

   greet("Charlie")  # Correct (1 parameter)
   greet("Charlie", "Bob")  # Error (2 parameters, but definition has 1)

Practice: Write a Function

Define a function area_of_rectangle that takes length and width as parameters and returns the area of a rectangle. Then call it to verify:

# Define the function
def area_of_rectangle(length, width):
    return length * width

# Call the function with parameters
length = 5
width = 3
area = area_of_rectangle(length, width)
print(f"Area of the rectangle: {area}")  # Expected output: 15

Summary

Functions are the core tool for code reuse in Python. After mastering function definition and calling, you can split complex logic into independent modules, making code cleaner and more maintainable. Later, explore advanced topics like default parameters, keyword arguments, or variable-length parameters, but building a solid foundation (understanding indentation, parameters, and return values) is key!

Xiaoye