Python v2 red and blue snakespython™v2

THE PYTHON V2 + PYHOPE FIELD GUIDE

50 things worth knowing

Not marketing fluff—50 compact, useful topics from your first print to closures, editor setup, CC0 sprites, DDA ray casting and a 9.4-million-pixel GPU frame.

Showing 50 of 50

01
Start

Hello, Python v2

Programs are plain .pyv2 files. print() accepts any number of values.

print("Hello, World!", 2 + 2)
02
Start

Run a file

Use the module command from the repository, or the pyv2 command after installing.

python3 -m pyv2 hello.pyv2
03
Start

Comments

A # comment runs to the end of the line and is ignored by the interpreter.

# explain why, not what
answer = 42
04
Values

Variables

Assignment creates a binding in the nearest function scope. No var keyword needed.

name = "Comet"
score = 10
05
Values

Numbers

Integers and decimals share one number type and print cleanly.

print(1, 2.5, 1e-3)
06
Values

Math operators

Use + - * / // % and **. Floor division and modulo follow Python rules.

print(10 / 4, 10 // 4, 7 % 3, 2 ** 8)
07
Values

Strings

Single or double quotes work. Escape special characters with a backslash.

title = "Python v2"
print(title.upper())
08
Values

F-strings

Prefix a string with f and place any expression inside braces.

name = "Ada"
print(f"Hello, {name}: {2 ** 8}")
09
Values

Booleans

The boolean literals are true and false, always lowercase.

ready = true
print(ready and not false)
10
Values

nil

nil is the deliberate nothing value. Safe map lookups return it when no default is given.

missing = nil
print(type(missing))
11
Flow

Truthiness

Zero, empty strings, empty lists, empty maps, false and nil are falsey.

if []: print("no") else: print("empty") end
12
Flow

if blocks

Open a block with a colon and close it with end. Indentation is for humans.

if score > 5:
    print("high")
end
13
Flow

elif and else

Chain choices without nesting another if.

if n < 0: print("negative")
elif n == 0: print("zero")
else: print("positive") end
14
Flow

Forward ternary

Python v2 puts the question first: condition ? yes : no.

label = score >= 60 ? "pass" : "retry"
15
Flow

while loops

Repeat while a condition remains truthy.

n = 3
while n > 0: print(n) n -= 1 end
16
Flow

break

break exits the nearest loop immediately.

while true:
    break
end
17
Flow

continue

continue skips the rest of this iteration and moves to the next.

for n in range(5):
    if n % 2 == 0: continue end
    print(n)
end
18
Flow

Loop over lists

for works with lists, strings, maps, and lazy ranges.

for name in ["Ada", "Grace"]: print(name) end
19
Flow

range

range(stop), range(start, stop), and range(start, stop, step) are lazy.

for i in range(10, 0, -2): print(i) end
20
Flow

Loop over text

Strings iterate Unicode characters instead of bytes.

for ch in "snake": print(ch) end
21
Data

List literals

Lists can contain any mixture of values and allow negative indexing.

items = [1, "two", true]
print(items[-1])
22
Data

push and pop

push appends and returns the list; pop removes and returns the last value.

xs = [1, 2]
xs.push(3)
print(xs.pop(), xs)
23
Data

Slices

slice(start, end) makes a new string or list and supports negative positions.

print([0, 1, 2, 3].slice(1, 3))
24
Data

Iterable toolkit

Sort, total, number, pair, or truth-test iterable values with concise builtins.

print([3, 1, 2].sort())
print(sum(range(5)))
print(enumerate(["a", "b"], 1))
print(zip([1, 2], ["a", "b"]))
25
Data

Map literals

Bare identifier keys become strings; quoted and computed keys work too.

hero = {name: "Ada", hp: 100}
26
Data

Map dot access

Read and write map keys with dots when the key is a valid identifier.

hero.city = "London"
print(hero.name, hero.city)
27
Data

Safe map get

get(key, default) avoids an error when optional data is absent.

print(hero.get("armor", 0))
28
Functions

Define functions

Use fn, parameters in parentheses, a colon, and end.

fn add(a, b):
    return a + b
end
29
Functions

Return values

return leaves the function immediately; no value means nil.

fn sign(n):
    if n < 0: return -1 end
    return 1
end
30
Functions

Real closures

Inner functions remember outer variables and assignment updates the existing binding.

fn counter():
 n = 0
 fn bump(): n += 1 return n end
 return bump
end
31
Functions

Recursion

A function can call itself. Base cases prevent infinite recursion.

fn fib(n):
 if n < 2: return n end
 return fib(n-1) + fib(n-2)
end
32
Functions

Anonymous functions

fn can be an expression, so callbacks stay compact.

square = fn(x): return x * x end
print(square(7))
33
Tools

String methods

Strings include upper, lower, title, trim, replace, contains, slice, and more.

print("  comet  ".trim().title())
34
Tools

split and join

Turn text into a list with split, then assemble it with list.join.

print("a,b,c".split(",").join(" - "))
35
Tools

Conversions

Use str, int, float, bool, repr, and type. Invalid numeric text raises ValueError.

print(int("42"), float("2.5"), type(true))
36
Tools

Assertions

assert is a normal function and accepts your own message.

assert(len([1, 2]) == 2, "list size changed")
37
Tools

Recover from errors

Catch runtime failures as maps with kind, message, line, and trace; finally always runs.

try: raise "stop"
catch error: print(error.kind, error.message)
finally: print("clean")
end
38
Tools

Use the REPL

Run pyv2 with no file for an interactive prompt; Ctrl-D exits.

python3 -m pyv2
39
Tools

Application CLI

Create, validate, and package production apps; pass arguments after the source filename.

pyv2 new windows-app "My App"
pyv2 check My-App
pyv2 build My-App
40
Tools

VS Code

The repository includes run/test tasks, file association, highlighting, and snippets.

Ctrl+Shift+B  # run current .pyv2 file
41
Tools

Dev containers

Choose Reopen in Container or create a Codespace; tests run after creation.

.devcontainer/devcontainer.json
42
Tools

Playground + Sudbury Workspace

The Playground builds responsive portfolios. The desktop app adds safe files, assets, editors, and Website, Game, CLI, or Windows EXE-ready project creation.

pyhope --studio
# New Project → Windows app
43
PyHope

Vec2

Immutable vectors provide addition, scaling, length, normalization, and dot products.

direction = Vec2(3, 4).normalized()
44
PyHope

TileMap

Text rows become collision worlds. Dots and spaces are open; other tiles are solid.

world = TileMap.from_text("###\n#.#\n###")
45
PyHope

Sprite

A sprite has a name, position, glyph, velocity, tags, and alive state.

hero = Sprite("hero", Vec2(1.5, 1.5), "@")
46
PyHope

Fixed-step Engine

Systems run before sprite movement each tick, making logic deterministic and testable.

@engine.system
def gravity(scene, dt): ...
47
PyHope

DDA ray casting

raycast walks the grid and reports the tile, distance, hit side, point, and step count.

hit = raycast(world, origin, direction)
48
PyHope

Free CC0 sprites

The original Comet Kid, Byte Beast, Null Slime, blaster, and coin are public domain.

assets/sprites/LICENSE.md
49
PyHope

9M GPU renderer

WebGL2 live mode is 720p; benchmark mode ray-casts 4096×2304 = 9,437,184 pixels.

games.html#gpu
50
Ship

Release software or games

Run tests, validate app metadata, create an integrity-tracked kit, then build the real EXE on Windows or publish games with GitHub Pages.

pyv2 check My-App
pyv2 build My-App --native

VIDEO TUTORIAL AT 1,000 SUBSCRIBERS

Prefer to learn by watching?

Subscribe to Cube Comet. The complete Python v2 + PyHope install video releases when the channel reaches 1K.

▶ Subscribe @CubeCometYT