python


What is a Function in Python? A function is a block of code that performs a specific task and can be reused whenever needed.

What is a Function in Python?

A function is a block of code that performs a specific task and can be reused whenever needed.
Python provides:

* Built-in functions (like `print()`, `len()`)
* User-defined functions (functions you create)



Why Use Functions?

* Avoid writing the same code multiple times
* Break programs into smaller, manageable parts
* Improve readability and debugging



Defining a Function in Python

Use the `def` keyword:


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


Call the function:


greet()  # Output: Hello, Welcome to Python!




Function with Parameters

Functions can take arguments (inputs):


def greet(name):
    print(f"Hello, {name}!")
    
greet("Alice")  # Output: Hello, Alice!




Function with Return Value

Functions can return a value using `return`:


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

result = add(5, 3)
print(result)  # Output: 8




Types of Arguments

Python supports different types of function arguments:

1. Positional Arguments


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

print(subtract(10, 5))  # Output: 5


2. Keyword Arguments


print(subtract(b=5, a=10))  # Output: 5


3. Default Arguments


def greet(name="Guest"):
    print(f"Hello, {name}!")

greet()       # Hello, Guest!
greet("John") # Hello, John!


4. Variable-Length Arguments

* `*args` → multiple positional arguments
* `kwargs` → multiple keyword arguments

Example:


def display(*args):
    print(args)

display(1, 2, 3)  # (1, 2, 3)




Lambda Functions

A lambda function is a small, anonymous function:


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




Built-in Functions

Python comes with many useful built-in functions:

* `len()` – length of a string or list
* `max()` – maximum value
* `sum()` – sum of numbers

Example:


numbers = [1, 2, 3]
print(sum(numbers))  # Output: 6




Scope of Variables

* Local variable → Defined inside a function
* Global variable → Defined outside any function

Example:


x = 10  # global

def func():
    x = 5  # local
    print(x)

func()  # Output: 5
print(x) # Output: 10




Summary

* Functions make code modular, reusable, and organized.
* Use `def` to define a function, `return` to return values.
* Understand arguments (`positional`, `keyword`, `default`, `*args`, `kwargs`).
* Use lambda functions for small tasks.