Sobes.tech
Intern
226

What is a function?

Answer from AI

sobes.tech AI

A function in Python is a named block of code that performs a specific task. It can accept arguments and return a value.

Main characteristics:

  • Reusability: Allows avoiding code duplication.
  • Modularity: Breaks down the program into smaller, manageable parts.
  • Abstraction: Hides implementation details, providing a simple interface.

Example of defining and calling a function:

# Function definition
def greet(name):
    return f"Hello, {name}!"

# Calling the function
message = greet("world")
print(message)  # Output: Hello, world!

Functions can be:

  • Built-in: Provided by Python itself (e.g., print(), len()).
  • User-defined: Created by the developer.
  • Anonymous (lambda functions): Small functions without a name.
# Example of a lambda function
multiply = lambda x, y: x * y
result = multiply(5, 3)
print(result)  # Output: 15