A function is a block of reusable code that performs a specific task. Think of a function as a mini-program within your main program. It helps you organize your code and make it more modular. To define a function, you use the `def` keyword followed by the name of the function and parentheses `()`. Here's an example:
def greet(): print("Hello, how are you?")
In this example, we defined a function called `greet()`. Whenever this function is called, it will print the message `"Hello, how are you?"`. To call or use a function, you simply write its name followed by parentheses `()`. For example:
greet() # Output: "Hello, how are you?"
Hello, how are you?
In this code, we called the `greet()` function, and it printed the message `"Hello, how are you?"`. Functions can also accept parameters, which are values that you can pass to the function when calling it. Parameters help you make your functions more flexible and reusable. Here's an example:
def greet(name): print("Hello, " + name + "! How are you?")
In this example, we defined a function called `greet()` that accepts a parameter called `name`. Such parameters are called function arguments. When calling this function, you need to provide a value for the `name` argument. For example:
greet("John") # Output: "Hello, John! How are you?"
Hello, John! How are you?
In this code, we called the `greet()` function and passed the value `"John"` as the `name` parameter. The function then printed the message `"Hello, John! How are you?"`. Functions can also return values using the `return` keyword. This allows us to get a result or output from a function and assign it to a variable. Here's an example:
def add_numbers(a, b): return a + b
In this example, we defined a function called `add_numbers()` that accepts two arguments `a` and `b`. The function returns the sum of `a` and `b`. To use the result of this function, you can assign it to a variable or use it in an expression. For example:
result = add_numbers(5, 3) print(result) # Output: 8
8
In this code, we called the `add_numbers()` function with the values `5` and `3`. The function returned the sum `8`, which we assigned to the variable `result`. These are just some basic concepts of functions in Python. Functions can be much more complex and can have multiple arguments, perform calculations, and even call other functions. Next, learn about using [keyword arguments](/tutorials/kwargs) in functions to specify default values for arguments, and improve clarity and readability.