Defining Functions in Python Using the def Keyword
Introduction
Functions are reusable blocks of code that perform a specific task. In Python, functions are defined using the def keyword. They make programs more modular, readable, and easier to maintain. This article explains how to define and use functions in Python with examples.
Syntax of a Function
The basic syntax of a function in Python is as follows:
def function_name(parameters): # Code block return result
Explanation:
- def: Keyword to define a function.
- function_name: Name of the function.
- parameters: Optional arguments the function takes (can be empty).
- return: Optional statement to return a result from the function.
Example: A Simple Function
The following example defines and calls a function that prints a greeting:
# Example of a simple function def greet(): print("Hello, World!") # Calling the function greet()
Output:
Hello, World!
Example: Function with Parameters
Functions can take parameters to make them more flexible. The following example demonstrates a function that takes a name as input:
# Function with parameters def greet_person(name): print(f"Hello, {name}!") # Calling the function with an argument greet_person("Alice")
Output:
Hello, Alice!
Example: Function with Return Value
A function can return a value using the return statement. The following example defines a function that calculates the square of a number:
# Function with return value def square(number): return number * number # Calling the function and storing the result result = square(4) print("The square is:", result)
Output:
The square is: 16
Example: Function with Default Parameters
Functions can have default parameter values. These are used if no argument is provided during the function call.
# Function with default parameter def greet_with_time(name, time_of_day="morning"): print(f"Good {time_of_day}, {name}!") # Calling the function with and without the second argument greet_with_time("Alice", "afternoon") greet_with_time("Bob")
Output:
Good afternoon, Alice! Good morning, Bob!
Example: Function with Multiple Parameters
The following example defines a function that adds two numbers:
# Function with multiple parameters def add_numbers(a, b): return a + b # Calling the function with two arguments sum_result = add_numbers(3, 7) print("The sum is:", sum_result)
Output:
The sum is: 10
Conclusion
Functions are a core feature of Python that make code more organized and reusable. By understanding how to define functions and use parameters and return values, you can write efficient and modular Python programs. Experiment with these examples to deepen your understanding of functions.