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.
The basic syntax of a function in Python is as follows:
def function_name(parameters): # Code block return result
Explanation:
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!
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!
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
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!
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
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.