A user-defined function is a reusable block of code that performs a specific task. You, the programmer, define the function once, and then you can "call" or "invoke" it whenever you need to perform that task. Functions are one of the most important tools for organizing your code, making it more readable, less repetitive, and easier to debug.
1. Defining and Invoking a Function
You define a function using the def keyword, followed by the function's name, parentheses (), and a colon :. The code that belongs to the function is indented. To run the function, you "call" it by writing its name followed by parentheses.
- Use Case: To group a set of instructions that you need to perform multiple times.
Python
# --- Defining and Invoking a Function ---
# This defines a simple function that prints a greeting.
def greet():
print("Hello! Welcome to the program.")
# Now, we can call the function to execute its code.
print("Calling the function for the first time:")
greet()
print("\nCalling the function again:")
greet()
2. Passing Parameters (Arguments)
Parameters are variables listed inside the function's parentheses. They act as placeholders for the values you will pass into the function when you call it. The values you pass in are called arguments.
- Use Case: To make a function more flexible by allowing it to operate on different data each time it's called.
Positional Arguments
These are the standard type of arguments. The values are passed to the function in the order they are listed.
Python
# --- Positional Arguments ---
# 'name' is a parameter.
def greet_user(name):
print(f"Hello, {name}!")
# "Alice" and "Bob" are arguments passed to the function.
greet_user("Alice")
greet_user("Bob")
Keyword Arguments
You can also pass arguments by specifying the parameter name, which allows you to pass them in any order.
Python
# --- Keyword Arguments ---
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
# The order doesn't matter when using keyword arguments.
describe_pet(pet_name="Whiskers", animal_type="cat")
Default Parameter Values
You can provide a default value for a parameter. If an argument for that parameter is not provided when the function is called, the default value is used.
Python
# --- Default Parameter Values ---
# 'country' has a default value of "India".
def user_profile(name, country="India"):
print(f"{name} is from {country}.")
user_profile("Rohit") # Uses the default value for country
user_profile("Neha", "USA") # Overrides the default value
3. Return Values: Void vs. Fruitful Functions
Fruitful Functions
A "fruitful" function is one that returns a value back to the part of the code that called it. This is done using the return keyword. The returned value can then be stored in a variable or used in other expressions.
- Use Case: When you need a function to perform a calculation and give you back the result.
Python
# --- Fruitful Function ---
def calculate_area(length, width):
area = length * width
return area # This sends the calculated value back.
# The returned value is stored in the 'rectangle_area' variable.
rectangle_area = calculate_area(10, 5)
print(f"The calculated area is: {rectangle_area}")
Void Functions
A "void" function is one that performs an action but does not explicitly return a value. In Python, these functions automatically return the special value None.
- Use Case: When you want a function to perform an action, like printing to the screen or modifying a list, but you don't need a result back.
Python
# --- Void Function ---
def print_greeting(name):
print(f"Hello, {name}!") # This function performs an action (printing).
# We can call it, but the return value is None.
result = print_greeting("Arjun")
print(f"The return value of the function is: {result}")
4. Scope of Variables: Global vs. Local
The "scope" of a variable determines where in your program it can be accessed.
Local Variables
Variables created inside a function are local to that function. They only exist while the function is running and cannot be accessed from outside the function.
Python
# --- Local Scope ---
def my_function():
# 'message' is a local variable.
message = "This is a local variable."
print(message)
my_function()
# The following line would cause a NameError because 'message' doesn't exist outside the function.
# print(message)
Global Variables
Variables created outside of any function are global. They can be accessed from anywhere in your script, including inside functions. However, if you want to modify a global variable from inside a function, you must use the global keyword.
Python
# --- Global Scope ---
# 'counter' is a global variable.
counter = 0
def increment_counter():
# Use the 'global' keyword to indicate we want to modify the global variable.
global counter
counter += 1
print(f"Inside the function, counter is now: {counter}")
print(f"Before calling the function, counter is: {counter}")
increment_counter()
print(f"After calling the function, counter is: {counter}")