Python Functions: Definition, Arguments, Lambda, Recursion & More

1. How do you define and call functions in Python?

Q: How to define and call functions?

Defining: Use the def keyword to create a function with a name, optional parameters, and a code block.

Syntax:

def function_name(parameters):
    # code block
    return value  # Optional
      

Calling: Invoke the function by its name with appropriate arguments (e.g., function_name(args)).

Properties: Functions are first-class objects (can be assigned to variables, passed as arguments).

Use Case: Reusing code for calculations or processing tasks.

2. Can you give an example of defining and calling functions?

# Defining and calling functions
def greet(name):
    message = f"Hello, {name}!"
    return message

# Calling the function
result = greet("Krishna")
print(result)

# Function without return
def print_info(age):
    print(f"Age: {age}")

print_info(30)
      

Output:

Hello, Krishna!
Age: 30
      

Note:

3. What are arguments and return values in Python functions?

Q: What are arguments and return values?

Arguments: Values passed to a function during a call, mapped to parameters in the function definition.

Types: Positional (order matters), keyword (name-based), default, variable-length.

Return Values: Data returned by a function using the return statement.

Use Case: Passing inputs to process data and retrieving results.

4. Can you give an example of arguments and return values?

# Arguments and return values
def calculate_salary(hours, rate):
    salary = hours * rate
    bonus = 500 if hours > 40 else 0
    return salary, bonus  # Returns a tuple

# Calling with positional arguments
total_salary, bonus = calculate_salary(45, 20)
print(f"Salary: ${total_salary}, Bonus: ${bonus}")

# Calling with keyword arguments
result = calculate_salary(rate=25, hours=30)
print(f"Result tuple: {result}")
      

Output:

Salary: $900, Bonus: $500
Result tuple: (750, 0)
      

Note:

5. What are default, keyword, and variable-length arguments in Python?

Q: What are default, keyword, and variable arguments?

Default Arguments: Parameters with default values; used if no argument is provided.

Syntax: def func(param=default).

Keyword Arguments: Arguments passed by parameter name, allowing flexible order.

Syntax: func(param1=value1, param2=value2).

Variable-Length Arguments: Allow passing an arbitrary number of arguments.

Use Case: Flexible function signatures for diverse inputs.

6. Can you give an example of default, keyword, and variable-length arguments?

# Default, keyword, and variable-length arguments
def employee_info(name, dept="IT", *args, **kwargs):
    details = f"Name: {name}, Dept: {dept}"
    if args:
        details += f", Skills: {args}"
    if kwargs:
        details += f", Extra: {kwargs}"
    return details

# Default argument
print(employee_info("Krishna"))

# Keyword argument
print(employee_info("Kristal", dept="HR"))

# Variable-length arguments
print(employee_info("Ram", "Sales", "Python", "SQL", role="Manager", salary=70000))
      

Output:

Name: Krishna, Dept: IT
Name: Kristal, Dept: HR
Name: Ram, Dept: Sales, Skills: ('Python', 'SQL'), Extra: {'role': 'Manager', 'salary': 70000}
      

Note:

7. What are *args and **kwargs in Python?

Q: What are *args and **kwargs?

*args: Collects non-keyword arguments into a tuple, allowing a function to accept any number of positional arguments.

Syntax: def func(*args).

**kwargs: Collects keyword arguments into a dictionary, allowing any number of named arguments.

Syntax: def func(**kwargs).

Use Case: Functions with dynamic argument counts (e.g., logging, data aggregation).

8. Can you give an example of *args and **kwargs?

# *args and **kwargs example
def process_data(*args, **kwargs):
    total = sum(args) if args else 0
    meta = kwargs if kwargs else {}
    return total, meta

# Using *args
total, meta = process_data(10, 20, 30)
print(f"Total: {total}, Meta: {meta}")

# Using **kwargs
total, meta = process_data(name="Krishna", role="Developer")
print(f"Total: {total}, Meta: {meta}")

# Using both
total, meta = process_data(5, 10, id=1, dept="IT")
print(f"Total: {total}, Meta: {meta}")
      

Output:

Total: 60, Meta: {}
Total: 0, Meta: {'name': 'Krishna', 'role': 'Developer'}
Total: 15, Meta: {'id': 1, 'dept': 'IT'}
      

Note:

9. What are lambda functions and recursion in Python?

Q: What are lambda functions?

Lambda functions are small anonymous functions defined with lambda arguments: expression.

Q: What is recursion?

Recursion occurs when a function calls itself to solve smaller subproblems, requiring a base case.

Q: Best practices for functions?

Frequently asked questions

How do you define and call functions in Python?

Use 'def function_name(parameters):' to define. Call with function_name(arguments). Functions can return values with 'return'.

What are arguments and return values in Python functions?

Arguments are inputs passed to parameters. Return sends output back; multiple values return as a tuple. No return implies None.

What are default, keyword, and variable-length arguments in Python?

Default: parameters with preset values. Keyword: passed by name. Variable-length: *args (positional tuple), **kwargs (keyword dict).

What are *args and **kwargs in Python?

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.

What are lambda functions in Python?

Anonymous inline functions defined with 'lambda arguments: expression'. Useful for short, throwaway functions.

What is recursion in Python?

A function calling itself to solve smaller instances of the same problem. Requires a base case to prevent infinite recursion.

What are best practices for Python functions?

Keep functions small and focused (single responsibility), use descriptive names, add doc strings, avoid side effects, handle errors.