A function is a block of reusable code that performs a specific task. Functions help organize code, reduce repetition, and improve readability. In Python, functions can have parameters, return values, and even be nested or anonymous.
1. Defining and Calling a Function
Syntax:
def function_name():
# Code block
Example:
def greet():
print("Hello, welcome to Python!")
greet() # Calling the function
Output:
Hello, welcome to Python!
2. Function with Parameters
Parameters allow a function to accept input values.
Syntax:
def function_name(param1, param2):
# Code block
Example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
greet("Bob")
Output:
Hello, Alice!
Hello, Bob!
3. Function with Return Value
A function can return a value using the return
statement.
Syntax:
pythonCopyEditdef function_name():
return value
Example:
def add(a, b):
return a + b
result = add(5, 3)
print("Sum:", result)
Output:
Sum: 8
4. Default Parameter Values
If a parameter is not provided, the function uses a default value.
Example:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Uses default value
greet("Charlie") # Uses provided value
Output:
Hello, Guest!
Hello, Charlie!
5. Keyword Arguments
Keyword arguments allow specifying parameters in any order.
Example:
def person_info(name, age):
print(f"Name: {name}, Age: {age}")
person_info(age=25, name="John")
Output:
Name: John, Age: 25
6. Variable-Length Arguments (*args
and **kwargs
)
*args
– Multiple Positional Arguments
Allows passing multiple values as a tuple.
def total_sum(*numbers):
return sum(numbers)
print(total_sum(1, 2, 3, 4))
Output:
10
**kwargs
– Multiple Keyword Arguments
Allows passing multiple named arguments as a dictionary.
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="New York")
Output:
name: Alice
age: 30
city: New York
7. Lambda (Anonymous) Functions
A lambda function is a small, single-line function without a name.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x * x
print(square(5))
Output:
25
8. Nested Functions
A function inside another function.
Example:
def outer_function():
def inner_function():
print("Inner function executed")
inner_function()
outer_function()
Output:
Inner function executed
9. Recursive Functions
A function that calls itself.
Example: Factorial Calculation
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Output:
120
10. Function Scope and global
Keyword
Variables inside functions are local unless declared global.
Example:
x = 10 # Global variable
def modify():
global x
x = 20 # Modify global variable
modify()
print(x) # Prints 20
Conclusion
- Functions help in code reusability and organization.
- They can have parameters, return values, and default arguments.
*args
handles multiple positional arguments, while**kwargs
handles keyword arguments.- Lambda functions are used for short, simple functions.
- Recursion enables solving problems like factorial calculation.