Control flow structures | Algorand Developer Portal

Control flow structures

Control flow in Algorand Python is similar to standard Python control flow, with support for if statements, while loops, for loops, and match statements.

If statements

If statements work the same as Python. The conditions must be an expression that evaluates to bool, which can include a String or Uint64 among others.

if condition:

# block of code to execute if condition is True

elif condition2:

# block of code to execute if condition is False and condition2 is True

else:

# block of code to execute if condition and condition2 are both False

See full example.

Ternary conditions

Ternary conditions work the same as Python. The condition must be an expression that evaluates to bool, which can include a String or Uint64 among others.

value1 = UInt64(5)

value2 = String(">6") if value1 > 6 else String("<=6")

While loops

While loops work the same as Python. The condition must be an expression that evaluates to bool, which can include a String or Uint64 among others.

You can use break and continue.

while condition:

# block of code to execute if condition is True

See full example.

For Loops

For loops are used to iterate over sequences, ranges and ARC-4 arrays. They work the same as Python.

Algorand Python provides functions like uenumerate and urange to facilitate creating sequences and ranges; in-built Python reversed method works with these.

Here is an example of how you can use these functions in a contract:

test_array = arc4.StaticArray(arc4.UInt8(), arc4.UInt8(), arc4.UInt8(), arc4.UInt8())

# urange: reversed items, forward index

for index, item in uenumerate(reversed(urange(4))):

test_array[index] = arc4.UInt8(item)

assert test_array.bytes == Bytes.from_hex("03020100")

See full examples.

Match Statements

Match statements work the same as Python with support for basic case/switch functionality. Captures and patterns are not supported. Pattern matching and guard clauses are also not supported currently.

match value:

case pattern1:

# block of code to execute if pattern1 matches

case pattern2:

# block of code to execute if pattern2 matches

case _:

# Fallback

See full example.