Expressions
Arithmetic
def main() -> None: print(1 + 2 * 3) # 7 print((1 + 2) * 3) # 9 print(10 - 3 - 2) # 5 print(-3 + 5) # 2Comparisons
a == ba != ba < ba <= ba > ba >= bChained comparisons are supported and each operand is evaluated once:
def main() -> None: print(1 < 2 < 3) # True print(5 < 4 < 3) # False print(1 < 2 + 3) # TrueBoolean operators
def main() -> None: print(True and False) print(True or False) print(not False) print(not 1 > 2) print(True or False and False)String operations
def main() -> None: word = "compiler" print(word[0]) # char print(word[3]) # char print(word[:4]) # slice → str print(word[4:]) print(word[0:4]) print(word[:]) print("a" + "b" + "c") # concatenation print(len("hello")) # length → int
# Postfix on literals and expressions print("hello"[1]) print("hello"[1:4]) print(("ab" + "cd")[1])String methods:
def main() -> None: value = "compiler" print(value.starts_with("com")) print(value.ends_with("ler")) print(value.find("pil")) print(value.split("pi")) print(value.replace("pile", "pact"))char / int conversion
import chars
def main() -> None: ch = "hello"[1] print(ch) print(ord(ch)) print(chr(65)) print(chars.is_digit('7')) print(chars.is_alpha('Q')) print(chars.is_space(' '))List and dict operations
See Types for the full list of available methods.
def main() -> None: xs: list[int] = [1, 2, 3] xs.append(4) xs.pop() xs.clear() print(len(xs))
colors: dict[str, str] = {"apple": "red"} colors["sky"] = "blue" colors.set("grass", "green") print(colors.contains("apple")) print("apple" in colors) print(colors.get_or("missing", "none")) print(colors.keys()) print(colors.values()) print(colors.items())Tuple indexing
Tuple indexing requires a non-negative integer literal:
def main() -> None: pair: (int, str) = (1, "hello") print(pair[0]) print(pair[1])Enum variant access
enum Color: RED GREEN
def main() -> None: print(Color.RED)Enum variant lookup is compile-time and module-aware.
Typed JSON calls
json.from_string[Type](text) and json.to_string(value) are compiler built-ins:
import json
class User: name: str age: int
def main() -> None: user = json.from_string[User]("{\"name\":\"ann\",\"age\":3}") print(user) print(json.to_string(user))