Home Tutorials Python Tutorial Functions
Functions

Functions


Definition: A function is a named, reusable block of code that only runs when it is explicitly called. You can pass data (parameters) into a function, and it can send data (return values) back as a result.

Why: Functions are a critical programming topic because they stop you from writing the same code over and over again. They break large, complicated programs down into smaller, organized, and much more readable pieces.

Syntax

def function_name(parameters):
    # code to execute
    return value

Example

def add(a, b):
    return a + b

# Calling the function and storing the result
result = add(10, 20)
print(result)

Explanation

  • The def Keyword: This tells Python that you are defining a new function.
  • Parameters: a and b are placeholders for the data that the function expects to receive when it is used.
  • The return Keyword: This exits the function and sends the calculated result back to the line where the function was called.
  • Function Call: add(10, 20) passes the actual numbers 10 and 20 into the function, which returns 30 to be stored in the result variable.

Key Notes

  • Defining a function does not run it. The code inside will only execute when you "call" or invoke the function by its name followed by parentheses (e.g., function_name()).
  • Functions do not strictly require a return statement. If no return is specified, the function automatically returns None.
  • A function must be defined higher up in your script before you try to call it.
Example

🏋️ Test Yourself With Exercises

Take our quiz on Functions to test your knowledge.

Exercise »