Functions, Arguments and Return Values
Scientific Python in GX-TXT · Module 2 · Lesson 11
A function collects instructions under a name and can be recalled several times with different data. This helps to give meaning to the steps, reduce repetitions and verify the results. We will create a function that builds a summary from the description of a Dataset GX-TXT.
Objectives: Define a function with def, pass arguments, use default values and return, document behavior and distinguish local calculations from effects on the Session.
Prerequisites: variables, dictionaries, conditions and calls to the APIs of previous lessons.
Define and call a function
def duration(sample_count, interval_s):
return (sample_count - 1) * interval_s
print(duration(4, 0.5)) # 1.5
def introduces the definition. sample_count and interval_s are parameters: names used in the function body. At the duration(4, 0.5), the 4 and 0.5 values are the topics. The indented block is executed when the function is called, not while the definition is read.
The example describes four synthetic snapshots separated by 0.5 seconds: between first and last there are three intervals, for a duration of 1.5 seconds. It’s not experimental data. The example function does not verify negative values or invalid types: a real application must define and control such predictions.
return is not print
return terminates the function and returns a value to the caller, which can assign it to a name or use it in another calculation. print shows text in output but, on its own, does not return that text as a result of the function. A function that comes to the end without return explicit returns None.
result = duration(4, 0.5)
print("Durata (s):", result)
Separating calculation and presentation allows you to reuse the result and control it. For example, duration(4, 0.5) == 1.5 is a control suitable for these exact values; for general floating point results, appropriate tolerance is required.
Position arguments, keywords and defaults
Topics can be passed by location, as above, or by name: duration(sample_count=4, interval_s=0.5). The keywords make the meaning explicit and can be useful when there are different parameters. A call must, however, respect the signature of the function.
A parameter can have a default value:
def etichetta(value, unit="mV"):
return f"{value} {unit}"
etichetta(1.2) uses mV; etichetta(1.2, unit="V") uses V text. The function does not convert the number: changing a label without converting the value is not a physical conversion. The defaults are evaluated when the function is defined; avoid mutable objects as shared blank lists such as defaults, unless that behavior is desired.
Documentation and local scope
A string immediately at the beginning of the body is a docstring and can describe purpose, arguments and result. Names assigned within a function are normally local to that call: they do not automatically become global names. You prefer to pass data through parameters and results, making explicit dependencies.
A pure function returns the same result for the same inputs without changing observable external status. A function that publishes a Dataset or changes the Session has external effects. The distinction helps to design controls: our summary works on the received dictionary and returns text; the separate API called law metadata by GX-TXT.
A function for a Dataset descriptor
CANONICAL_DATASET_API_v2/describe returns the dataset metadata required. Our example reads the Synthetic Dataset created in lesson 9 and passes the dictionary to summarize_dataset function. The function checks that there is a non-empty identifier and a number of rows other than None; if one of the two is missing, it returns Descrizione incompleta.
This is a minimum control, not a complete validation of the scheme: it does not control for example that row_count is a non-negative whole or that variables have consistent units. The name of the unit parameter in the example is a text label of the count, not a physical drive of the data.
Full code
from gxtxt import gxtxt_api_call, gxtxt_api_require
def summarize_dataset(description, unit="righe"):
"Returns a summary, without changing the Session."
identifier = description.get("dataset_id")
rows = description.get("row_count")
if not identifier or rows is None:
return "Description incomplete"
return f"{identifier}: {rows} {unit}"
gxtxt_api_require("CANONICAL_DATASET_API_v2@2")
data_values = gxtxt_api_call("CANONICAL_DATASET_API_v2", "describe", ["corso_python_serie_sintetica"])
print("Dataset:", summarize_dataset(data_values))
print("With explicit label:", summarize_dataset(data_values, unit="osservazioni"))
print("Incomplete example:", summarize_dataset({"dataset_id": "prova"}))
rows is None control is intentional: a zero-line dataset is not an incomplete description automatically. The third call passes a synthetic dictionary without row_count and shows the expected error branch.

The function is separated from the call that reads the descriptor in the Session.
Execution
- Open the Session with the Synthetic Dataset of lesson 9 and choose Viewers → Python Scripts.
- Import
dataset_functions.py, assigns name and Script ID into thesessionbroom, then saves. - Open Run → Open Script Runner… and press Run Job.
- In the output, it controls the two dataset reepylogues and the
Descrizione incompletaresponse for the test dictionary. At the Course Session, the Dataset has four lines.

The same function is called with the default label, with a keyword and incomplete input.
Common error
If you write print(result) into a function but forget return result, the call shows the value but returns None. If then the caller tries to use that result as a number, the program does not behave as expected. Choose explicitly what the function must return and what, possibly, must show.
Exercise
Write duration(sample_count, interval_s=1.0) that returns the duration between the first and last sample. Calculate the result for four samples with default interval and 0.5 s range, assuming at least one sample.
Worked solution
def duration(sample_count, interval_s=1.0):
return (sample_count - 1) * interval_s
print(duration(4)) # 3.0
print(duration(4, interval_s=0.5)) # 1.5Four samples delimit three intervals: with 1 s the result is 3 s, with 0.5 s is 1.5 s. An implementation for external data must control the sample_count >= 1 hypothesis and units.
In the next lesson, we will exhibit typified parameters in the GX-TXT Runner.