← Back to Dashboard

Functions Lambda Expressions: Concept Notes

"""
Topic 04: Functions & Lambda Expressions - Concept Notes

Functions are reusable blocks of code that perform a specific task. They help in making code modular, readable, and dry(Don't Repeat Yourself).

1. Defining Functions
   - Use the 'def' keyword.
   - Functions can take parameters(input) and return values(output).

2. Arguments
   - Positional arguments: Order matters.
   - Keyword arguments: Passed as key=value.
   - Default arguments: Provide a fallback value.
   - *args and **kwargs: For a variable number of arguments.

3. Scope
   - Local scope: Variables defined inside a function.
   - Global scope: Variables defined outside any function.

4. Lambda Expressions
   - Anonymous, one-line functions.
   - Syntax: lambda arguments: expression
"""

__PH_2__
def greet(name="User"):
    return f"Hello, {name}!"

print(greet("Alice"))
print(greet()) __PH_3__

__PH_4__
def add_numbers(a, b):
    return a + b

__PH_5__
def sum_all(*numbers):
    return sum(numbers)

print(f"Sum: {sum_all(1, 2, 3, 4, 5)}")

__PH_6__
square = lambda x: x * x
print(f"Square of 5: {square(5)}")

__PH_7__
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(f"Evens: {evens}")

__PH_8__
def multiply(a, b):
    \"\"\"Multiplies two numbers and returns the result.\"\"\"
    return a * b

print(multiply.__doc__)