Functions in Python are blocks of code that can be called and executed repeatedly throughout a program. Functions are useful for encapsulating code that performs a specific task, making it easier to read and maintain your code.
Here is an example of a simple function in Python:
python
# Define a function
def greet(name):
print("Hello, " + name + "!")
# Call the function
greet("Alice") # Output: "Hello, Alice!"
greet("Bob") # Output: "Hello, Bob!"
In this example, the `greet()` function takes one argument (`name`) and prints a personalized greeting to the console. The function is then called twice, each time with a different argument, producing different output.
Functions can also return a value, which can be used in other parts of your program. Here is an example:
python
# Define a function that returns a value
def square(x):
return x ** 2
# Call the function and use the returned value
result = square(5)
print(result) # Output: 25
In this example, the `square()` function takes one argument (`x`) and returns the square of that number. The function is then called with the argument `5`, and the returned value is assigned to the variable `result`. Finally, the value of `result` is printed to the console.
Functions can also have default parameter values, which are used if the function is called without providing a value for that parameter. Here is an example:
python
# Define a function with default parameter values
def greet(name="World"):
print("Hello, " + name + "!")
# Call the function with and without an argument
greet() # Output: "Hello, World!"
greet("Alice") # Output: "Hello, Alice!"
In this example, the `greet()` function has a default parameter value of “World”. If the function is called without an argument, the default value is used; otherwise, the provided argument is used.
Python also provides the ability to define functions with variable-length argument lists (`*args` and `**kwargs`), which can be useful for functions that need to handle a variable number of arguments.