Scientific Python in GX-TXT · Module 2 · Lesson 8

A script often has to choose what to do based on the available data. In this lesson we turn the Booleans of the previous lesson into ramifications: if one condition is true we execute a block, otherwise we choose another. We will apply the mechanism to a GX-TXT API verification.

Objectives: to write if, elif and else blocks; to understand the order of conditions and indentation; to build useful messages when a requirement is missing.

Prerequisites: comparisons, Booleans and API controls of lesson 7.

A choice with if

sample_count = 4
if sample_count >= 2:
    print("At least two samples are available")

Python evaluates the condition after if. If it is true, execute the indented block under the two points; if it is false, skip the block. Indentation is not only aesthetic: it indicates which instructions belong to the branch. Use four spaces per level and avoid mixing tabs and spaces.

The number of samples is synthetic. The condition controls only a quantity: it does not certify the quality of the observations or the statistical adequacy of the experiment.

An alternative to else

if sample_count >= 2:
    print("Calculatable interval")
else:
    print("We need at least two samples.")

Only one branch is executed. The else does not have its own condition: it covers all cases where the condition of the if is false. Choose messages that explain what is missing, instead of producing an arbitrary number to fill the result.

More cases with elif

elif shorts ‘else if’ and introduces a further condition:

temperatura_c = 22.0
if temperatura_c < 0:
    print("Under zero")
elif temperatura_c < 30:
    print("From zero to less than thirty degrees Celsius")
else:
    print("Thirty degrees Celsius or more")

The conditions are evaluated from above to bottom: the first true case is its block and the others are jumped. In this example, the second branch is only achieved if the first condition is false. The boundaries count: 0 belongs to the second range, 30 to the third. These thresholds are didactic choices, not safety limits for an experiment.

Delayed blocks and initial controls

A if can contain another if; each level requires additional indentation. For simple conditions, a if/elif/else chain is often more readable. In one function, an initial control can stop work with a message or exception when a prerequisite is missing; we will see return and the structure of the functions in the next lessons.

Avoid confusing the presence of a value with its validity: a non-empty list may contain unusable data; a zero measure may be valid. Choose the predicate according to the meaning of the condition.

Choose based on GX-TXT features

In the example we control the public API CANONICAL_DATASET_API_v2 and the operation list. If the API is not registered, we show a message. If the API is present but does not offer the operation, we show another one. In the remaining case we request version 2 with gxtxt_api_require and read the descriptor via gxtxt_api_describe.

The presence of the operation concerns the functionality declared by the bridge: it does not guarantee that a specific Dataset is scientifically valid. The descriptor contains structured information; we use .get to read the identifier and version, as in lesson 5.

Full code

from gxtxt import gxtxt_api_has, gxtxt_api_has_operation, gxtxt_api_describe, gxtxt_api_require

api = "CANONICAL_DATASET_API_v2"
if not gxtxt_api_has(api):
    print("API not available:", api)
elif not gxtxt_api_has_operation(api, "list"):
    print("API present, operation list not available")
else:
    gxtxt_api_require("CANONICAL_DATASET_API_v2@2")
    description = gxtxt_api_describe(api)
    print("API ready:", description.get("api_id"))
    print("Versione:", description.get("api_version"))
    print("Operation list available")

The first branch signals the absence of the API, the second the absence of the operation. Only in the last branch are required the version requirement and the descriptor. If the version requirement fails, the exception must be read and managed according to the context: the API must not be declared ready. Certain verifications of literal requirements may be made by GX-TXT before the start of the script; in this case an unavailable requirement may prevent the execution before the branches are evaluated.

Conditional branches and API checks in the GX-TXT Python editor.
Conditional branches and API checks in the GX-TXT Python editor.

The if/elif/else structure in the editor with the Rich Dark theme.

Execution

  1. Open a Session and Viewers → Python Scripts.
  2. Import conditional_api_checks.py, assigns a name and a Script ID into the session broom, then saves.
  3. Open Run → Open Script Runner…, press Run Job and watch the output.
  4. The API and the operation are shown in the installation: the else branch is executed and the 2 version is shown. A different installation may show another outcome or refuse an unsatisfied requirement.
Output of the branch executed for the Dataset API.
Output of the branch executed for the Dataset API.

The selected branch communicates the API and the version detected.

Common error

A else must align with its if and end with the two points. If the indentation is inconsistent, Python may report IndentationError or the code may belong to a different block than expected. Reread alignment and check cases at borders, not only the most common case.

Exercise

For a synthetic number of n readings, nessuna read_result printing if n is zero, una read_result if it is one and più letture in other non-negative cases. Try values 0, 1 and 4.

Worked solution
n = 4
if n == 0:
    print("no reading")
elif n == 1:
    print("a reading")
else:
    print("more readings")

For 0, 1 and 4 the first, second and third branch are selected respectively. This example assumes n not negative; a program that receives external input should also control negative numbers and type of value.

In the next lesson we will use the cycles to cross the elements of a catalog.

Download the Module 2 scripts (ZIP)

#Control Flow #GX-TXT #Python

Other steps of this project

Leave a Reply

Your email address will not be published. Required fields are marked *