Python functions with example

Python functions are blocks of code that can be called repeatedly to perform a specific task. They help to organize code into smaller, reusable pieces and make it more readable and maintainable. Here’s an example of a Python function:

def greet(name):
    """This function greets the person passed in as a parameter."""
    print("Hello, " + name + ". How are you?")

greet("John")

In this example, we define a function called greet that takes one parameter called name. The function then prints a greeting message to the console, using the parameter name to personalize the message.

When we call the function by passing the value "John" as the argument, the output will be:

Hello, John. How are you?

Let’s take a closer look at how this function works. The def keyword is used to define a function, followed by the name of the function (greet in this case). Inside the parentheses, we define the function’s parameter(s) (name in this case). The code inside the function is indented to indicate that it’s part of the function. In this case, we’re simply printing a message to the console.

The """ before and after the docstring (a brief description of what the function does) is a way to document the function’s purpose, parameters, and return value. It’s always a good practice to document your functions so that other people (and your future self) can understand what your code does.

Finally, we call the function by passing the value "John" as the argument. This means that the name parameter inside the function will be set to "John". The function then prints the greeting message to the console using this value.

That’s a basic example of a Python function. You can create more complex functions with multiple parameters, loops, conditional statements, and so on, depending on what you want to achieve.

Leave a Reply