Functions in Python: User-Defined

Mannan Ul Haq
0

In Python, a function is a block of organized and reusable code that is used to perform a single, related action. Functions provide modularity for applications and promote code reusability.


Defining a Function:

You can define a function using the `def` keyword followed by the function name and a pair of parentheses.


def function_name(parameters):
    # Function body
    return [expression]  # Optional return statement


Examples:


1. Simple Function (Without Parameters):


def greet():
    print("Hello!")

greet()  # Outputs: Hello!


2. Function with Parameters:


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

greet("Alice")  # Outputs: Hello, Alice


3. Function with Return Value:


def add(a, b):
    return a + b

result = add(3, 4)
print(result)  # Outputs: 7



Arguments:

Positional Arguments: The most common arguments that are passed to functions and are assigned to the respective parameters based on their position.


def subtract(a, b):
    return a - b

print(subtract(5, 3))  # Outputs: 2


Keyword Arguments: Allow you to specify the name of the argument when calling the function.


print(subtract(b=3, a=5))  # Outputs: 2


Default Arguments: Provide a default value for a parameter.


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

greet()         # Outputs: Hello, Guest
greet("Bob")    # Outputs: Hello, Bob


Variable-length Arguments: Allow you to pass an arbitrary number of arguments.

  • `*args` (Non-Keyword Arguments)
  • `**kwargs` (Keyword Arguments)


def print_args(*args, **kwargs):
    print(args)      # Outputs a tuple
    print(kwargs)    # Outputs a dictionary

print_args(1, 2, 3, a=4, b=5)



Lambda Functions:

These are small, anonymous functions defined using the `lambda` keyword. They can have multiple arguments but only one expression.


The syntax for a lambda function is:


lambda arguments: expression


Examples:


1. A simple lambda function:


x = lambda a: a + 10
print(x(5))  # Outputs: 15


2. Lambda with multiple arguments:


multiply = lambda a, b: a * b
print(multiply(5, 3))  # Outputs: 15



Recursive Functions:

A function that calls itself is a recursive function.


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

print(factorial(5))  # Outputs: 120


Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !