Home Browser Contributors

Function

A function is a way to create reusable pieces of code that can have variables inputted into. Python has hundreds of functions built-in, a couple example include print() and sort(). You can also write your own functions in Python to add your own reusable operations.

Defining Functions

Let's define our own function in Python. First, think of a easy name to remember and one that won't conflict with built-in functions. Next, you'll want to type in def and then the function name along with a set of parenthesis and a colon that end. Finally create a new indented line and start writing code!

Example

``` py def myFunction(): # Define function print("It works!") return myFunction() # Call function later ```

Parameters

In Python, you can also create functions that take variables as an input. You can use this to write a long piece of code once and use it anywhere easily.

Example

Here's an example of a very basic logging function, which takes a message and a severity number:

``` py def log(message, severity=0): severityLevels = ["Info", "Warn", "Error"] print(f"[{severityLevels[severity]}] {message}") log("Logging works!", 0) ```