Course Overview

/

Python Functions

Python Functions

By introducing functions into a script it is possible to create small sections of code that perform a specific task. Functions are used to make code more modular, easier to read, and easier to reuse. By dividing a program into smaller, independent functions, it becomes easier to understand and maintain the program as a whole.

A function is defined using the def keyword, followed by the function name and a set of parentheses. The parentheses can contain any arguments that the function needs to take as input. The body of the function is indented and contains the code that performs the desired task.

One of the benefits to using functions is the ability to write code once and call it in multiple locations throughout a script. It is also possible to combine functions together to create more advanced actions without having to add too much complexity to the scripting process.

Python has many built-in functions that can be used immediately. Print is an example of an built-in function that can be called within a Python script.

3rd Python Script

The third Python script created is:

These functions each provide a small block of code to conduct an action with the variables provided.

Function 1

Function 1 is a simple function that declares the x and y variables and will print the output of x multiplied by y

Function 2

Function 2 introduces a parameter that will be defined during execution. By using the code

it is possible to define a parameter called “name” that will be used within function2. To execute function 2 and pass the parameter value the command is

Function 3

Function 3 demonstrates the ability to have multiple parameters used by a function that are defined at execution. This is achieved with the code

to execute function 3 and provide the values for both x and y the command is

Function 4

Function 4 introduces the concept of the “return” key word. While the other functions all include the use of the print function to display the output, it is possible to use the “return” function to store the output of the function without having to print to the terminal.

It is then possible to chain together functions to achieve a goal.

For function 4, there is no output displayed to the user until the print function is used to call function 4