If#

class gamspy.If(condition: Expression | Condition | Operation | MathOp | Parameter)[source]#

Bases: object

A context manager to conditionally execute a group of statements.

The If class maps to the GAMS if statement. It allows you to branch conditionally around a group of execution statements within a loop.

Parameters:
conditionExpression

The logical condition that must be satisfied to execute the nested statements.

Examples

1. Skipping iterations conditionally:

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, records=[f"i{idx}" for idx in range(1, 11)])
>>> cnt = gp.Parameter(m, records=0)
>>> with gp.Loop(i) as loop:
...     with gp.If(gp.math.mod(gp.Ord(i), 2) == 0):
...         loop.Continue
...     cnt[...] += 1

2. Breaking a loop based on a condition:

>>> with gp.Loop(i) as loop:
...     with gp.If(i.sameAs("i6")):
...         loop.Break
...     cnt[...] += 1