Functions

1.4. Functions#

In Python, a function is a block of code that can be reused multiple times throughout a program. Functions are useful for organizing and structuring code, and for breaking down complex tasks into smaller, more manageable pieces.

Below are some examples of common built-in Python functions and what they do:

  • print() Prints input to screen

  • type() Returns the type of the input

  • abs() Returns the absolute value of the input

  • min() Returns the minimum value of the input. (input could be a list, tuple, etc.)

  • max() Same as above, but returns the maximum value

  • sum() Returns the sum of the input (input could be a list, tuple, etc.)

Here is a step-by-step guide on how to create any function in Python:

Step 1: Define the function using the def keyword, followed by the function name, and a set of parentheses.

Step 2: Define the code block that will be executed when the function is called. This code block should be indented underneath the function definition. For example:

def greet():
    print("Hello, World!")

Step 3: (Optional) Add parameters to the function, which are values that can be passed into the function when it is called. These parameters are defined within the parentheses of the function definition. For example:

def greet(name):
    print("Hello, " + name + "!")

Step 4: (Optional) Add a return statement to the function, which is used to return a value or an expression from the function. For example:

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

Step 5: Call the function by using the function name, followed by a set of parentheses. For example:

greet("John Weller")
Hello, John Weller!

Thus, to create and use the function we write it all in one cell as follows:

def greet(name):
    print("Hello, " + name + "!")

greet("John")
greet("Mary Jane")
Hello, John!
Hello, Mary Jane!

In this example, the function greet() is defined with one parameter name, the function is called twice, first with “John” as an argument, then with “Mary” as an argument, the function will print out a greeting message each time it’s called –> the input of the created function is the argument and the output is the greeting message.

Functions are essential to programming, they allow you to organize, structure and reuse your code in an efficient and readable way.