# Variable declarations
counter = 0
items = ["a", "b", "c"]
# Function definitions
def process_item(item):
return item.upper()
# Block definitions
de worker(10):
# Executes exactly 10 times
print(f"Working: {worker.current_iteration}")
fo background():
# Runs forever until stopped
print("Background task")
sleep(1)
os utility():
# Runs once when called
print("One-shot execution")
# Required main block
main:
# Program entry point
worker.start()
background.start()
utility()
when worker.status == "COMPLETED":
exit()
# Numbers
integer = 42
decimal = 3.14
# Strings
text = "Hello"
fstring = f"Value: {integer}"
# Booleans
flag = True
condition = False
# Collections
list_data = [1, 2, 3]
tuple_data = (1, 2, 3)
dict_data = {"key": "value"}
set_data = {1, 2, 3}
# None
empty = None
when condition:
# Execute when true
when not condition:
# Execute when false
when x > 10 and y < 5:
# Multiple conditions
when item in collection:
# Membership testing
result = value_if_true when condition else value_if_false
status = "pass" when score >= 70 else "fail"
Type | Syntax | Execution | Use Case |
---|---|---|---|
Main | main: |
Continuous loop | Program orchestration |
Forever | fo name(): |
Until stopped | Background tasks |
Declarative | de name(N): |
Exactly N times | Fixed iterations |
One-shot | os name(): |
Once when called | Utility functions |
Parallel FO | parallel fo name(): |
Forever in thread | CPU-intensive work |
Parallel DE | parallel de name(N): |
N times in thread | Batch processing |
# Starting blocks
block_name.start()
# Stopping blocks
block_name.stop()
# State management
block_name.save() # Save current state
block_name.savestop() # Save and stop
block_name.startsave() # Start from saved state
block_name.discard() # Remove saved state
# Block properties
block_name.current_iteration # Current iteration count
block_name.status # "RUNNING", "STOPPED", "COMPLETED"
block_name.iterations # Total iterations (DE blocks)
block_name.has_saved_state # Boolean
items = ["a", "b", "c", "d"]
index = 0
os process_all():
when index < len(items):
print(f"Processing: {items[index]}")
index = index + 1
process_all() # Recursive call
main:
process_all()
data = [1, 2, 3, 4, 5]
data_count = len(data)
de process_data(data_count):
item = data[process_data.current_iteration]
print(f"Item {process_data.current_iteration}: {item}")
main:
process_data.start()
queue = []
producer_done = False
parallel fo producer():
queue.append("item")
sleep(1)
when len(queue) >= 10:
producer_done = True
break
parallel fo consumer():
when len(queue) > 0:
item = queue.pop(0)
print(f"Consumed: {item}")
when producer_done and len(queue) == 0:
break
progress = 0
de long_task(100):
progress = progress + 1
# Save every 10 steps
when progress % 10 == 0:
long_task.save()
# Handle errors
when error_occurred:
long_task.savestop()
fix_error()
long_task.startsave()
print(*values)
- Output to consoleinput(prompt)
- Read user inputopen(file, mode)
- Open fileint(value)
- Convert to integerfloat(value)
- Convert to floatstr(value)
- Convert to stringbool(value)
- Convert to booleanlen(collection)
- Get lengthlist(iterable)
- Create listtuple(iterable)
- Create tupledict(pairs)
- Create dictionaryset(iterable)
- Create setabs(x)
- Absolute valuemin(iterable)
- Minimum valuemax(iterable)
- Maximum valuesum(iterable)
- Sum valuesround(x, digits)
- Round numberrange(start, stop, step)
- Number sequenceenumerate(iterable)
- Index-value pairszip(*iterables)
- Combine iterablessorted(iterable)
- Sort collectionreversed(sequence)
- Reverse sequencesleep(seconds)
- Pause executionexit()
- Terminate programsafe_call(func, *args)
- Safe function callresult = risky_operation()
when result["success"]:
data = result["data"]
process_data(data)
when not result["success"]:
error = result["error"]
print(f"Error: {error}")
handle_error()
result = safe_call(potentially_failing_function, arg1, arg2)
when is_success(result):
value = get_result(result)
print(f"Success: {value}")
when not is_success(result):
error = get_error(result)
print(f"Failed: {error}")
# Python modules
import os
import math
from datetime import datetime
# WHEN modules
import my_module
from game_engine import Player, create_sprite
# Usage
my_module.my_function()
my_module.my_block.start()
# Process each item
items = ["a", "b", "c"]
item_count = len(items)
de process_each(item_count):
item = items[process_each.current_iteration]
result = process_item(item)
print(f"Processed: {item} -> {result}")
state = "idle"
fo state_machine():
when state == "idle":
when trigger_condition:
state = "active"
when state == "active":
do_work()
when work_complete:
state = "done"
when state == "done":
cleanup()
state = "idle"
events = []
running = True
fo event_processor():
when running and len(events) > 0:
event = events.pop(0)
handle_event(event)
fo event_generator():
when running:
new_event = check_for_events()
when new_event:
events.append(new_event)
sleep(0.01)
fo busy_wait():
when condition:
break
sleep(0.01) # Add small delay
de batch_processor(total_items):
# Process multiple items per iteration
start_idx = batch_processor.current_iteration * batch_size
end_idx = min(start_idx + batch_size, total_items)
process_batch(items[start_idx:end_idx])
parallel de cpu_work(num_tasks):
# CPU-intensive work in separate thread
result = expensive_calculation(cpu_work.current_iteration)
results.append(result)
debug = True
when debug:
print(f"[DEBUG] Variable state: {variable}")
print(f"[DEBUG] Block status: {block.status}")
fo debug_monitor():
print(f"Active blocks: {len(running_blocks)}")
print(f"Memory usage: {get_memory_info()}")
sleep(5)
error_log = []
when error_occurred:
error_log.append({
"time": datetime.now(),
"error": error_message,
"context": current_state
})
This quick reference covers the most commonly used features and patterns in WHEN programming. For detailed explanations and more examples, refer to the full documentation sections.