In Python, functions are blocks of reusable code that perform a specific task. They allow you to break down your code into smaller, more manageable pieces, making it easier to read, write, test, and maintain. Functions are defined using the def keyword followed by the function name and parentheses containing any parameters the function accepts. Here's a basic overview of Python functions:
You can define a function using the def keyword followed by the function name and parentheses containing any parameters the function accepts. The function body is indented below.
def greet(name):
print("Hello, " + name + "!")
You call a function by using its name followed by parentheses containing any arguments the function requires.
greet("Alice") # Output: Hello, Alice!
Functions can return values using the return statement. You can return multiple values as a tuple.
def add(a, b):
return a + b
result = add(3, 5)
print(result) # Output: 8
You can specify default values for function parameters. Parameters with default values become optional.
def greet(name="World"):
print("Hello, " + name + "!")
greet() # Output: Hello, World!
greet("Alice") # Output: Hello, Alice!
You can call functions using keyword arguments, where you explicitly specify the name of the parameter along with its value.
def greet(first_name, last_name):
print("Hello, " + first_name + " " + last_name + "!")
greet(last_name="Smith", first_name="John") # Output: Hello, John Smith!
You can define functions that accept a variable number of arguments using *args or **kwargs.
def my_func(*args):
for arg in args:
print(arg)
my_func("apple", "banana", "cherry") # Output: apple banana cherry
Lambda functions are small, anonymous functions defined using the lambda keyword.
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
You can add documentation to your functions using docstrings. Docstrings are strings that appear as the first statement in a function body.
def greet(name):
"""
This function greets the user.
"""
print("Hello, " + name + "!")
You can add type annotations to function parameters and return values to specify the expected types.
def add(a: int, b: int) -> int:
return a + b
These are some common features and practices when working with functions in Python. Functions play a crucial role in organizing code and promoting code reusability.