FUNCTIONS
FUNCTIONS
Functions in Python are reusable blocks of code that perform a specific task.
They help in organizing the code, making it more modular, readable, and
maintainable. Here’s an overview of functions in Python:
1. Defining a Function
You define a function using the def keyword followed by the function name,
parentheses, and a colon. The function body is indented.
def greet():
print("Hello, World!")
● This defines a simple function named greet that prints "Hello, World!".
2. Calling a Function
You call a function by using its name followed by parentheses.
greet()
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
greet("Bob")
● This defines a function greet that takes one parameter name and prints a
personalized greeting.
result = add(3, 5)
print(result) # Output: 8
● This defines a function add that takes two parameters, adds them, and
returns the result.
5. Default Parameters
You can provide default values for parameters, making them optional.
def greet(name="World"):
print(f"Hello, {name}!")
6. Keyword Arguments
You can call functions using keyword arguments, specifying parameter names
explicitly.
greet(first_name="Alice", last_name="Smith")
greet(last_name="Doe", first_name="John")
7. Variable-Length Arguments
Variable-length arguments in Python allow you to pass a variable number of
arguments to a function. This is done using *args for positional arguments and
**kwargs for keyword arguments.
def greet(*names):
print(f"Hello, {name}!")
In this example:
def print_details(**details):
print(f"{key}: {value}")
In this example:
You can combine *args and **kwargs in a single function to handle both types
of variable-length arguments.
Example:
print("Positional arguments:")
print("\nKeyword arguments:")
print(f"{key}: {value}")
In this example:
total = sum(prices)
return total
Syntax
Example
add = lambda a, b: a + b
print(add(3, 5)) # Output: 8
def calculate_area(radius):
return 3.14 * radius * radius
r=5
area = calculate_area(r)
print(f"The area of a circle with radius {r} is {area}")