Conditionals

PyTeal provides two conditional expressions, the simple branching If expression, and Cond expression for chaining tests.

Simple Branching: If

In an If expression,

If(test-expr, then-expr, else-expr)

the test-expr is always evaludated and needs to be typed TealType.uint64. If it results in a value greater than 0, then the then-expr is evaluated. Otherwise, else-expr is evaluated.

An If expression must contain a then-expr and an else-expr; the later is not optional.

Chaining Tests: Cond

A code:Cond expression chians a series of tests to select a result expression. The syntax of Cond is:

Cond([test-expr body],
     . . . )

Each test-expr is evaluated in order. If it produces 0, the paired body is ignored, and evaluation proceeds to the next test-expr. As soon as a test-expr produces a true value (> 0), its body is evaluated to produce the value for this Cond expression. If none of test-expr s evaluates to a true value, the Cond expression will be evaluated to err, a TEAL opcode that causes the runtime panic.

In a Cond expression, each test-expr needs to be typed TealType.uint64. A body could be typed either TealType.uint64 or TealType.bytes. However, all body s must have the same data type. Otherwise, a TealTypeError is triggered.

Example:

Cond([Global.group_size() == Int(5), bid],
     [Global.group_size() == Int(4), redeem],
     [Global.group_size() == Int(1), wrapup])

This PyTeal code branches on the size of the atomic transaction group.