WHEN Language Syntax

Variables and Data Types

Variable Declaration

# Simple assignment
name = "Alice"
age = 25
is_active = True
scores = [85, 92, 78]
person = {"name": "Bob", "age": 30}

Supported Types

  • Numbers: 42, 3.14
  • Strings: "hello", 'world'
  • Booleans: True, False
  • None: None
  • Lists: [1, 2, 3]
  • Tuples: (1, 2, 3)
  • Dictionaries: {"key": "value"}

String Features

# Regular strings
message = "Hello World"

# F-strings for interpolation
name = "Alice"
greeting = f"Hello {name}!"

# Raw strings
path = r"C:\Users\name\file.txt"

# Multi-line strings
text = """
This is a
multi-line string
"""

Operators

Arithmetic

result = 10 + 5    # Addition
result = 10 - 5    # Subtraction
result = 10 * 5    # Multiplication
result = 10 / 5    # Division
result = 10 // 3   # Floor division
result = 10 % 3    # Modulo

Comparison

when x == y:       # Equal
when x != y:       # Not equal
when x < y:        # Less than
when x > y:        # Greater than
when x <= y:       # Less than or equal
when x >= y:       # Greater than or equal

Logical

when x and y:      # Logical AND
when x or y:       # Logical OR
when not x:        # Logical NOT

Membership

when item in list:     # Contains
when item not in list: # Does not contain

Control Flow

Conditional Execution

# Basic conditional
when temperature > 30:
    print("Hot day!")

when temperature <= 30:
    print("Nice weather")

# Nested conditions
when weather == "sunny":
    when temperature > 25:
        print("Perfect beach day!")
    when temperature <= 25:
        print("Good for walking")

Ternary Operator

# Conditional expression
status = "hot" when temperature > 30 else "cold"
message = f"Today is {status}"

Function Definitions

Basic Functions

def greet(name):
    print(f"Hello, {name}!")
    return f"Greeted {name}"

def add(a, b=0):
    return a + b

# Function calls
greet("Alice")
result = add(5, 3)

Function Parameters

def process_data(data, format="json", verbose=False):
    when verbose:
        print(f"Processing {len(data)} items as {format}")

    # Process data
    return processed_data

# Call with positional and keyword arguments
result = process_data(my_data, format="xml", verbose=True)

Collections and Indexing

List Operations

items = ["apple", "banana", "cherry"]

# Indexing
first = items[0]
last = items[-1]

# Slicing
subset = items[1:3]    # ["banana", "cherry"]
first_two = items[:2]  # ["apple", "banana"]

# Modification
items.append("date")
items[0] = "apricot"

Dictionary Operations

person = {"name": "Alice", "age": 25}

# Access
name = person["name"]
age = person.get("age", 0)

# Modification
person["city"] = "New York"
person.update({"job": "Engineer"})

Tuple Unpacking

# Multiple assignment
a, b, c = [1, 2, 3]
x, y = get_coordinates()

# In function parameters
def process_point():
    coordinates = get_point()
    x, y = coordinates
    return x + y

Exception Handling Patterns

WHEN uses conditional patterns instead of try/catch:

# Check before operation
when file_exists(filename):
    content = read_file(filename)
    when content:
        process_content(content)
    when not content:
        print("File is empty")

when not file_exists(filename):
    print("File not found")

# Using result checking
result = safe_operation()
when result["success"]:
    data = result["data"]
    print(f"Success: {data}")
when not result["success"]:
    error = result["error"]
    print(f"Error: {error}")

Import Statements

Python Modules

import os
import sys
from math import sqrt, pi
from datetime import datetime as dt

# Module usage
current_dir = os.getcwd()
square_root = sqrt(16)

WHEN Modules

# Import WHEN file
import my_module

# Use imported functions and blocks
my_module.my_function()
my_module.my_block.start()

# From import
from game_engine import create_sprite, move_sprite

Comments

# Single line comment

# Multi-line comments use multiple # lines
# This is a longer explanation
# that spans several lines

"""
Block comments using triple quotes
are also supported for documentation
"""

Global Variables

counter = 0

def increment():
    global counter
    counter = counter + 1

# In WHEN, most variables are implicitly global
# within the interpreter scope

Class Definitions

class Player:
    health = 100

    def __init__(self, name):
        self.name = name

    def take_damage(self, amount):
        self.health = self.health - amount
        when self.health <= 0:
            print(f"{self.name} is defeated!")

# Create instance
player = Player("Hero")
player.take_damage(25)

Special Syntax Notes

  1. Indentation: Uses Python-style indentation with spaces
  2. Case Sensitivity: Variable and function names are case-sensitive
  3. Keywords: when, main, fo, de, os, parallel are reserved
  4. Line Endings: Statements end at newlines (no semicolons needed)
  5. String Quotes: Both single and double quotes supported

Built-in Functions

I/O Functions

# Input/Output
name = input("Enter your name: ")
print("Hello", name)
print(f"Your name is {name}")

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

Type Conversion

# Type conversion
num = int("42")
text = str(123)
decimal = float("3.14")
flag = bool(1)

Collection Functions

# Built-in functions
length = len([1, 2, 3])
maximum = max([1, 5, 3])
minimum = min([1, 5, 3])
total = sum([1, 2, 3])