Calling a function to compute statistics in a prompt

Building functions into your prompts significantly widens what you can do with a model. You can write a request that includes a call to specific functions, which automates more complex processes.

The task:

Call a function that takes an array of numbers as input and returns the main statistical measures (mean, median, mode, standard deviation).

The prompt:

Write a Python function that takes an array of numbers and returns the mean, the median, the mode and the standard deviation. Then call this function on the array [12, 15, 12, 14, 15, 18, 12, 20].

Result:

The Python function

Python
import statistics
def calculate_statistics(numbers): mean = statistics.mean(numbers)
median = statistics.median(numbers) mode = statistics.mode(numbers)
stdev = statistics.stdev(numbers)
return mean, median, mode, stdev

The array of numbers

Python
numbers = [12, 15, 12, 14, 15, 18, 12, 20]

The function call

Python
result = calculate_statistics(numbers) result

When working with functions, state clearly which parameters the function should take and what output format you expect. That helps the model produce a function that is ready to use straight away, with no extra rework.

Try it in GPTunneL