Function in Python

Function Python

In Python, a function is a block of code that performs a specific task and can be called by other code. Functions can take arguments (also called parameters) as input and return a value as output.

Here is an example of a simple function in Python that takes two numbers as arguments and returns their sum:

def add(x, y):
  return x + y

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

Functions can also have default values for their arguments, which means that the caller does not have to provide a value for that argument when calling the function. If a default value is not specified, the argument is required.

def add(x, y=10):
  return x + y

result = add(3)
print(result)  # Output: 13

Functions can also be called with keyword arguments, which allows the caller to specify the values of the arguments by name instead of position.

result = add(y=5, x=2)
print(result)  # Output: 7

There are many other features and techniques for defining and using functions in Python. They can be an essential part of writing modular, reusable, and maintainable code.

Leave a Reply