Functions are reusable blocks of code that perform specific tasks. They help organize your programs and avoid repeating the same code multiple times.
Creating a Function
Use the def keyword to create a function:
def greet():
print("Hello, World!")
# Call the function
greet() # Output: Hello, World!
Functions with Parameters
Parameters allow functions to work with different inputs:
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice") # Hello, Alice!
greet_person("Bob") # Hello, Bob!
Functions with Return Values
Functions can return results for later use:
def add_numbers(a, b):
result = a + b
return result
sum_result = add_numbers(5, 3)
print(sum_result) # 8
Default Parameters
Provide default values for parameters:
def introduce(name, age=25):
print(f"Hi, I'm {name} and I'm {age} years old.")
introduce("Charlie") # Uses default age
introduce("Diana", 30) # Uses provided age
Multiple Return Values
Python functions can return multiple values:
def calculate(a, b):
sum_val = a + b
diff_val = a - b
return sum_val, diff_val
result1, result2 = calculate(10, 3)
print(result1) # 13
print(result2) # 7
Function Best Practices
Write clear, focused functions that do one thing well:
def calculate_area(length, width):
"""Calculate the area of a rectangle."""
return length * width
area = calculate_area(5, 3)
print(f"Area: {area} square units")
Functions make your code modular, easier to test, and more maintainable.