Python def Keyword
In Python, the def
keyword is used to define functions. A function is a block of reusable code that performs a specific task. Using functions helps keep code organized, reduces redundancy, and makes programs easier to read and maintain.
Syntax
def function_name(parameters):
"""Optional docstring"""
# Function body
return value # (Optional) Return statement
Components of a Function
Component | Description |
---|---|
def | Keyword used to define a function. |
function_name | Name of the function (should be meaningful and follow Python naming conventions). |
parameters | Optional values passed to the function for processing. |
docstring | Optional multi-line string that describes what the function does. |
function body | Contains the statements that define the function’s behavior. |
return | Optional statement that sends a value back to the caller. |
Return Value
A function may or may not return a value. If a function has a return
statement, it sends the computed result back to the caller. Otherwise, it returns None
by default.
Examples
1. Defining and Calling a Simple Function
In this example, we define a function that prints a message and then call it.
We use the def
keyword to define a function called greet
. The function does not take any parameters and simply prints “Hello, Python!”. To execute the function, we call it by writing its name followed by parentheses: greet()
.
def greet():
print("Hello, World!")
# Calling the function
greet()
Output:
Hello, World!
2. Function with Parameters
We can pass values (parameters) to functions to customize their behavior.
Here, we define a function greet_user
that takes a parameter name
. When the function is called, it prints a greeting message using the provided name.
def greet_user(name):
print("Hello,", name, "!")
# Calling the function with an argument
greet_user("Arjun")
Output:
Hello, Arjun!
3. Function with Return Value
Functions can return values using the return
statement.
Here, we define a function square
that takes a number as input and returns its square. The return
statement sends the computed value back to the caller.
def square(num):
return num * num
# Calling the function and storing the returned value
result = square(4)
print("Square of 4:", result)
Output:
Square of 4: 16
4. Handling Errors: Missing Arguments
If a function expects an argument but is called without one, Python raises a TypeError
.
def greet_user(name):
print("Hello,", name, "!")
# Calling the function without an argument (this will raise an error)
try:
greet_user()
except TypeError as e:
print("Error:", e)
Output:
Error: greet_user() missing 1 required positional argument: 'name'
To fix this, we should always provide an argument when calling the function or define a default parameter value.
5. Function with Default Parameter
We can provide default values for parameters so that the function works even if an argument is not provided.
Here, the greet_user
function has a default value of "Guest"
for the name
parameter. If no argument is provided, it uses the default value.
def greet_user(name="Guest"):
print("Hello,", name, "!")
# Calling function with and without argument
greet_user("Arjun")
greet_user() # Uses default value
Output:
Hello, Arjun!
Hello, Guest!
Using default values makes functions more flexible and prevents errors when arguments are missing.