Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Function

Function

A function in Python is a block of reusable code that performs a specific task. Functions help make programs more organized, modular, and reusable.

Types of Functions in Python

  • Built-in Functions – Predefined functions like print(), len(), max(), etc.
  • User-defined Functions – Functions created by the user.
  • Lambda Functions – Anonymous functions with a single expression.

1. Defining and Calling a Function

A function is defined using the def keyword.

Example: Simple Function

def greet():
    print("Hello, welcome to Python!")

greet()  # Calling the function

Output:

Hello, welcome to Python!

2. Function with Parameters

Functions can accept parameters (arguments) to work with different values.

Example: Function with Parameters

def greet(name):
    print("Hello,", name)

greet("Alice")
greet("Bob")

Output:

Hello, Alice
Hello, Bob

  • name is a parameter, and "Alice" and "Bob" are arguments.

3. Function with Return Value

A function can return a value using the return statement.

Example: Function Returning a Value

def add(a, b):
    return a + b  # Returns the sum

result = add(5, 3)
print("Sum:", result)

Output:

Sum: 8

The return keyword sends the result back to the caller.

4. Default Parameter Values

You can set default values for parameters.

Example: Default Parameter

def greet(name="Guest"):
    print("Hello,", name)

greet()  # Uses default value
greet("Alice")  # Uses given argument

Output:

Hello, Guest
Hello, Alice

  • If no argument is provided, Guest is used.

5. Function with Multiple Arguments (*args and **kwargs)

  • *args allows multiple positional arguments.
  • **kwargs allows multiple keyword arguments.

Example: Using *args

def add_numbers(*args):
    return sum(args)

print(add_numbers(10, 20, 30, 40))  # Adds multiple numbers

Output:

100

Example: Using **kwargs

def display_info(**kwargs):
    for key, value in kwargs.items():
        print(key, ":", value)

display_info(name="Alice", age=25, city="New York")

Output:

name : Alice
age : 25
city : New York

6. Lambda (Anonymous) Functions

A lambda function is a small, one-line function.

Example: Lambda Function

square = lambda x: x * x
print(square(4))  # Output: 16

Equivalent to:

 def square(x):
    return x * x

7. Recursive Function

A function that calls itself is called recursion.

Example: Factorial Using Recursion

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # Output: 120

  • Factorial Calculation: 5!=5×4×3×2×1=120

Conclusion :

  • Use functions to avoid repetition and make code modular.
  • return helps send a value back from a function.
  • *args and **kwargs help handle multiple arguments.
  • lambda is useful for small functions.

    Leave a Reply

    Your email address will not be published.

    Need Help?