# Simple assignment
name = "Alice"
age = 25
is_active = True
scores = [85, 92, 78]
person = {"name": "Bob", "age": 30}
42
, 3.14
"hello"
, 'world'
True
, False
None
[1, 2, 3]
(1, 2, 3)
{"key": "value"}
# 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
"""
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
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
when x and y: # Logical AND
when x or y: # Logical OR
when not x: # Logical NOT
when item in list: # Contains
when item not in list: # Does not contain
# 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")
# Conditional expression
status = "hot" when temperature > 30 else "cold"
message = f"Today is {status}"
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)
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)
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"
person = {"name": "Alice", "age": 25}
# Access
name = person["name"]
age = person.get("age", 0)
# Modification
person["city"] = "New York"
person.update({"job": "Engineer"})
# 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
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 os
import sys
from math import sqrt, pi
from datetime import datetime as dt
# Module usage
current_dir = os.getcwd()
square_root = sqrt(16)
# 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
# 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
"""
counter = 0
def increment():
global counter
counter = counter + 1
# In WHEN, most variables are implicitly global
# within the interpreter scope
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)
when
, main
, fo
, de
, os
, parallel
are reserved# 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
num = int("42")
text = str(123)
decimal = float("3.14")
flag = bool(1)
# Built-in functions
length = len([1, 2, 3])
maximum = max([1, 5, 3])
minimum = min([1, 5, 3])
total = sum([1, 2, 3])