Why does Python code run faster in a function?

Python code can run faster in a function because of something called "Just-In-Time" (JIT) compilation. When a function is called, the Python interpreter converts the bytecode for that function to machine code, which can then be executed directly by the computer's CPU. This process, known as "compilation," can improve the performance of the code by reducing the overhead of the interpreter. Additionally, if the function is called multiple times, the compiled machine code can be reused, further improving performance.

Watch a course Python - The Practical Guide

Here's an example of a simple function in Python:

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

result = add_numbers(3, 4)
print(result)

In this example, the add_numbers function is defined and then called with the arguments 3 and 4. The function takes these two numbers, adds them together, and returns the result, which is then printed to the console. When the function is called, the Python interpreter will convert the bytecode for the function to machine code, which can then be executed directly by the CPU.