WHEN Standard Library Reference

Built-in Functions

Input/Output Functions

print(*values)

Print values to standard output.

print("Hello World")
print("Name:", name, "Age:", age)
print(f"Score: {score}")

input(prompt="")

Read a line from standard input.

name = input("Enter your name: ")
age_str = input("Enter your age: ")
age = int(age_str)

open(filename, mode="r")

Open a file for reading or writing.

# Reading
file = open("data.txt", "r")
content = file.read()
file.close()

# Writing
file = open("output.txt", "w")
file.write("Hello World")
file.close()

# Using with statement
with open("data.txt", "r") as file:
    content = file.read()

Type Conversion Functions

int(value)

Convert value to integer.

number = int("42")
number = int(3.14)    # Returns 3
number = int(True)    # Returns 1

float(value)

Convert value to floating-point number.

decimal = float("3.14")
decimal = float(42)   # Returns 42.0

str(value)

Convert value to string.

text = str(42)        # "42"
text = str(3.14)      # "3.14"
text = str(True)      # "True"

bool(value)

Convert value to boolean.

flag = bool(1)        # True
flag = bool(0)        # False
flag = bool("")       # False
flag = bool("text")   # True

Collection Functions

len(collection)

Return the length of a collection.

length = len([1, 2, 3])       # 3
length = len("hello")         # 5
length = len({"a": 1, "b": 2}) # 2

list(iterable)

Create a list from an iterable.

numbers = list(range(5))      # [0, 1, 2, 3, 4]
chars = list("hello")         # ['h', 'e', 'l', 'l', 'o']

tuple(iterable)

Create a tuple from an iterable.

coords = tuple([1, 2])        # (1, 2)
letters = tuple("abc")        # ('a', 'b', 'c')

dict(iterable)

Create a dictionary.

pairs = [("a", 1), ("b", 2)]
mapping = dict(pairs)         # {"a": 1, "b": 2}

set(iterable)

Create a set from an iterable.

unique_numbers = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3}
unique_chars = set("hello")                 # {'h', 'e', 'l', 'o'}

Mathematical Functions

abs(number)

Return absolute value.

positive = abs(-5)    # 5
positive = abs(3.14)  # 3.14

min(iterable) / min(a, b, ...)

Return minimum value.

smallest = min([3, 1, 4, 1, 5])  # 1
smallest = min(3, 1, 4)          # 1

max(iterable) / max(a, b, ...)

Return maximum value.

largest = max([3, 1, 4, 1, 5])   # 5
largest = max(3, 1, 4)           # 4

sum(iterable, start=0)

Sum values in an iterable.

total = sum([1, 2, 3, 4, 5])     # 15
total = sum([1, 2, 3], 10)       # 16 (starts with 10)

round(number, ndigits=0)

Round a number to given precision.

rounded = round(3.14159)         # 3
rounded = round(3.14159, 2)      # 3.14

Utility Functions

range(start, stop, step=1)

Generate a sequence of numbers.

numbers = list(range(5))         # [0, 1, 2, 3, 4]
numbers = list(range(1, 6))      # [1, 2, 3, 4, 5]
numbers = list(range(0, 10, 2))  # [0, 2, 4, 6, 8]

enumerate(iterable, start=0)

Return enumerated pairs.

items = ["a", "b", "c"]
for i, item in enumerate(items):
    print(f"{i}: {item}")
# 0: a
# 1: b
# 2: c

zip(*iterables)

Zip iterables together.

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
pairs = list(zip(names, ages))
# [("Alice", 25), ("Bob", 30), ("Charlie", 35)]

sorted(iterable, key=None, reverse=False)

Return sorted list.

numbers = sorted([3, 1, 4, 1, 5])        # [1, 1, 3, 4, 5]
words = sorted(["apple", "Banana"], key=str.lower)  # ["apple", "Banana"]

reversed(sequence)

Return reversed iterator.

backwards = list(reversed([1, 2, 3]))    # [3, 2, 1]
backwards = list(reversed("hello"))      # ['o', 'l', 'l', 'e', 'h']

Error Handling Functions

Safe Operation Functions

safe_call(function, *args, **kwargs)

Safely call a function and return result with error handling.

result = safe_call(int, "42")
when result["success"]:
    number = result["result"]
when not result["success"]:
    error = result["error"]
    print(f"Error: {error}")

is_success(result)

Check if safe_call operation succeeded.

result = safe_call(operation)
when is_success(result):
    print("Operation successful")

get_result(result)

Extract result value from safe_call.

result = safe_call(calculate_something)
when is_success(result):
    value = get_result(result)
    print(f"Calculated: {value}")

get_error(result)

Extract error message from safe_call result.

result = safe_call(risky_operation)
error = get_error(result)
when error:
    print(f"Operation failed: {error}")

WHEN-Specific Functions

Block Management

sleep(seconds)

Pause execution for specified seconds.

sleep(1)       # Pause for 1 second
sleep(0.5)     # Pause for 500ms
sleep(0.016)   # Pause for ~60 FPS frame

exit()

Exit the WHEN program.

when error_condition:
    print("Fatal error occurred")
    exit()

globals()

Access global variable namespace.

global_vars = globals()
global_vars["new_variable"] = "value"

File System Operations

File Reading/Writing

# Read entire file
with open("data.txt", "r") as f:
    content = f.read()

# Read lines
with open("data.txt", "r") as f:
    lines = f.readlines()

# Write file
with open("output.txt", "w") as f:
    f.write("Hello World\n")
    f.write(f"Current time: {datetime.now()}")

# Append to file
with open("log.txt", "a") as f:
    f.write("New log entry\n")

File Operations (via os module)

import os

# Check if file exists
when os.path.exists("file.txt"):
    print("File exists")

# Check if it's a file or directory
when os.path.isfile("path"):
    print("It's a file")
when os.path.isdir("path"):
    print("It's a directory")

# List directory contents
files = os.listdir(".")
for filename in files:
    print(filename)

# Create directory
os.makedirs("new_directory", exist_ok=True)

# Get file size
size = os.path.getsize("file.txt")

# Get current working directory
cwd = os.getcwd()

# Change directory
os.chdir("/path/to/directory")

Time and Date Functions

import time
from datetime import datetime, timedelta

# Current time
now = datetime.now()
timestamp = time.time()

# Format time
formatted = now.strftime("%Y-%m-%d %H:%M:%S")

# Sleep (pause execution)
time.sleep(1)        # 1 second
time.sleep(0.1)      # 100 milliseconds

# Time calculations
future = now + timedelta(days=7)
past = now - timedelta(hours=2)

# Measure execution time
start_time = time.time()
# ... do work ...
elapsed = time.time() - start_time

Random Number Generation

import random

# Random integer
num = random.randint(1, 10)      # 1 to 10 inclusive

# Random float
decimal = random.random()        # 0.0 to 1.0
decimal = random.uniform(1, 5)   # 1.0 to 5.0

# Random choice from list
items = ["apple", "banana", "cherry"]
choice = random.choice(items)

# Random sample (multiple items)
sample = random.sample(items, 2)  # 2 random items

# Shuffle list in-place
random.shuffle(items)

# Set random seed for reproducibility
random.seed(42)

Mathematical Operations

import math

# Constants
pi = math.pi
e = math.e

# Trigonometric functions
sin_val = math.sin(math.pi / 2)    # 1.0
cos_val = math.cos(0)              # 1.0
tan_val = math.tan(math.pi / 4)    # 1.0

# Logarithms
log_val = math.log(10)             # Natural log
log10_val = math.log10(100)        # Base 10 log (2.0)

# Power and roots
sqrt_val = math.sqrt(16)           # 4.0
pow_val = math.pow(2, 3)           # 8.0

# Rounding
ceil_val = math.ceil(3.2)          # 4
floor_val = math.floor(3.8)        # 3

# Degrees/radians conversion
degrees = math.degrees(math.pi)    # 180.0
radians = math.radians(180)        # pi

JSON Handling

import json

# Parse JSON string
json_text = '{"name": "Alice", "age": 30}'
data = json.loads(json_text)
name = data["name"]  # "Alice"

# Convert to JSON string
python_data = {"score": 95, "passed": True}
json_output = json.dumps(python_data)

# Read JSON file
with open("data.json", "r") as f:
    data = json.load(f)

# Write JSON file
with open("output.json", "w") as f:
    json.dump(python_data, f, indent=2)

String Operations

String Methods

text = "Hello World"

# Case operations
upper = text.upper()          # "HELLO WORLD"
lower = text.lower()          # "hello world"
title = text.title()          # "Hello World"
swapped = text.swapcase()     # "hELLO wORLD"

# Checking string properties
is_alpha = text.isalpha()     # False (contains space)
is_digit = "123".isdigit()    # True
is_lower = text.islower()     # False

# String searching
index = text.find("World")    # 6
index = text.index("World")   # 6 (raises exception if not found)
count = text.count("l")       # 3

# String modification
replaced = text.replace("World", "Universe")  # "Hello Universe"
stripped = "  hello  ".strip()               # "hello"
split_text = text.split(" ")                 # ["Hello", "World"]
joined = "-".join(["a", "b", "c"])          # "a-b-c"

# String formatting
padded = text.ljust(20, "*")    # "Hello World*********"
padded = text.rjust(20, "*")    # "*********Hello World"
padded = text.center(20, "*")   # "****Hello World*****"

Data Structures

Collections Module

from collections import defaultdict, Counter, deque

# Default dictionary
dd = defaultdict(list)
dd["key"].append("value")  # Automatically creates list

# Counter for counting items
counter = Counter(["a", "b", "a", "c", "b", "a"])
most_common = counter.most_common(2)  # [("a", 3), ("b", 2)]

# Deque for efficient append/pop from both ends
queue = deque([1, 2, 3])
queue.appendleft(0)    # [0, 1, 2, 3]
queue.append(4)        # [0, 1, 2, 3, 4]
first = queue.popleft()  # 0

This completes the comprehensive standard library reference for the WHEN programming language. The library combines Python's extensive standard library with WHEN-specific functions for block management, safe error handling, and the unique execution model of the language.