primopy
primopy is a place to learn Python in your web browser. There is nothing to install, no account to create, and nothing to set up. You open the page, you write a few lines, you press a button, and you see what happens.
Most tools only show you what your program printed. primopy also shows you what it did: every step of a run lands on the execution tape, with every variable on screen, and you can travel the tape forwards and backwards, line by line or one operation at a time. If you have never programmed before, that is the feature to get to know first.
There is more around it. A tutor sits beside the editor; it sees your code, your output and the step you are on, and it answers with a question rather than the solution. Teachers can hand out a whole project as a single link, and put quiz questions inside it for the tutor to ask. Drawings and charts appear next to the code, and a guided tour shows you the whole thing the first time you open it.
Contents#
- 1Your first five minutes
- 2Primo, the guided tour
- 3What's in the header
- 4The examples
- 5Writing code in the editor
- 6Running your program
- 7Stepping through your program
- 8Output, plots and drawings
- 9Programs that ask questions:
input() - 10Working with several files
- 11Package management
- 12The Python console, a calculator for trying things
- 13Code completion
- 14Undo
- 15The tutor
- 16Quizzes
- 17Documents and notebooks
- 18Is my work saved?
- 19Changing the layout and theme
- 20Keyboard shortcuts
- 21Things primopy can't do
- 22When something goes wrong
1Your first five minutes#
Open the page. In the tab row under the editor you'll see Downloading Python… for a few seconds, then Ready. Now Run and Record, at the top left, work.
Try this:
- Open the Examples menu in the header and pick 6 · Find the bug.
- Switch Record on, then press Run.
- Press Step ▶ a few times. Watch the Variables box on the right: it shows every variable and its current value, and highlights the ones that just changed.
- Went one step too far? Press ◀ Back.
That program calculates an average, and gets it wrong. Instead of staring at the code trying to work out why, you can simply watch the numbers change until you spot the moment things go astray. This is how you'll want to look at your own programs too.
2Primo, the guided tour#
The coiled snake in the logo is Primo. The first time you open primopy he uncoils, crawls across the screen and stops at each part of the interface to explain it. Press Next (or Enter, or →) to send him on; pressed while he is still typing or pressing buttons, he finishes at once. Back (or ←) takes him to the stop before, shown as it was when he had finished there: the program he typed, the run and the drawing are back as they were. Enter always sends him on, after Back too: the keyboard is on Next again. Skip or Escape ends the tour.
The tour uses two small example projects and an empty file to have something to show: it does a sum at the console, runs example 1, types a sun in an orange sky into an empty file to show off completion and the drawing, then loads example 5 and records it, to travel through the run step by step, forth and back, and to walk through one line with Detail, whose value shows in a box under the line; before it says goodbye, it points at the project button beside the logo, whose list is where a project is shared by link, downloaded as a ZIP, or, in Chrome and Edge, saved to a folder. Don't worry about your own work: the tour never touches your project, and when it is over, your files come back exactly as you left them. Nor does it run anything in Python: the console's answers, the runs it shows, and what completion lists, were recorded beforehand and are played back, so the variables you had at the console are still there when the tour is over. Only the console runs your own code meanwhile: Run on anything but the tour's examples, Shift+Enter and the document's runs wait until the tour is over, and the button with the project's name does nothing.
You can call Primo back any time by clicking the logo or pressing the Tour button in the header.
3What's in the header#
The header reads left to right: first the two buttons that start your program, then everything you do to a project.
| Control | What it does |
|---|---|
| primopy logo | Click to start the tour. Hover to see the version and whether your work is being saved |
| Project name | The project you are in, beside a briefcase. Click for the list of your projects: open another, rename it, delete it, download it as a ZIP or copy a link to it, or start a new one, empty (New project), from files or a ZIP (From files or a ZIP…) or, in Chromium browsers (Chrome, Edge, Brave, Opera), from a folder on your computer (From a folder…). The project you are in shows its files as a tree (each with a tick box, a document file with its chapter book as its icon); over the files sit New file, Open files and Run (which file Run starts), on the line of Files the project's folder (Save to a folder…, in Chromium browsers), and over their tick boxes, after with:, Link to this project (a chain link) and, below it, Download; the project's row has Rename and Delete. A small drive after the name means the project is linked to a folder on your computer: green while it saves there, yellow while it waits for Reconnect |
| Run | Runs your program. It wears the same yellow mark as the file tab it starts from |
| Record | A switch. While it is on, Run records every step, and the button turns yellow and its mark becomes a record dot |
| Examples | Opens a ready-made example program as a project of its own |
| Undo | Takes back your last change. When that change would bring files back, it turns dark blue and reads Restore 2 files |
| Tour | Starts the guided tour |
| Handbook | Opens this handbook in a new tab |
| Tutor | Shows or hides the tutor chat |
| ◐ / ☀ / ☾ | Switches the look: follow the system, light, dark |
The status (Downloading Python → Ready → Running → Finished, or a short error message) is not in the header. It sits in the tab row under the editor, right of Output / Plots / Display / Draw, next to what it is talking about.
4The examples#
The examples are short, complete programs, each about one idea. They're the best way to learn what primopy and Python can do. Pick one, read it, run it, step through it, then change something and run it again.
| # | What it shows |
|---|---|
| 1 | Variables and print |
| 2 | Drawing shapes on a canvas |
| 3 | Lists and loops: adding up numbers, building a new list |
| 4 | Drawing a pattern with a loop |
| 5 | Functions, and how one function calls another |
| 6 | Finding a real bug by stepping through the program |
| 7 | Drawing a whole scene |
| 8 | A program that asks the user a question with input() |
| 9 | A program split over two files |
| 10 | Numbers with numpy and a plot with matplotlib |
| 11 | Organising code in a folder (a "package") |
| 12 | Reading a text file and writing a new one |
| 13 | Adding to a log file every time the program runs |
| 14 | Reading a table from a CSV file and writing a report |
| 15 | Conway's Game of Life, drawn cell by cell |
| 16 | Snake: a game loop that reads the keyboard |
An example opens as a project of its own, and your project stays as it was: the button beside the logo names the project you are in and takes you back to any other (see Is my work saved?). Where the browser keeps only one project, an example replaces the files in it instead, and Undo brings your files straight back if you didn't mean to; it says Restore 2 files when that is what it would do.
The last menu entry, · new project ·, starts a project with one empty file; nothing is deleted. In a browser that keeps only one project (see Is my work saved?), examples replace that project as described, and the last entry reads · clear saved work ·: it deletes everything you've saved (after asking) and leaves you an empty file.
5Writing code in the editor#
The big text area in the middle is where you write your program. It colours Python code to make it easier to read and helps with a few tedious things:
- Enter starts the new line at the same indentation as the one above, and indents one level further after a line that ends in
:(likeif,for,def). - Tab inserts four spaces, the standard Python indentation. If you're in the middle of typing a name, Tab completes it instead (see Code completion).
- Shift+Tab removes one level of indentation.
- Click a line number to select the whole line; Shift+click selects every line up to that one.
- Click just left of a line number to place a red dot, a breakpoint. With Record off, your program stops when it reaches that line and waits for you (see Stopping at a breakpoint). With Record on, it runs to the end, the tape opens at the first dot it passed, and Continue ▶▶ jumps from one dot to the next. Handy for skipping straight to the interesting part.
If you edit the code after recording a run, the recording is thrown away: it no longer matches what's on screen. Just record again.
Folding a block away#
In a Python file, a small triangle ▾ appears to the right of the line number wherever a block starts: a def, a class, a loop, an if, or a list or dictionary spread over several lines. The triangles are faint until you move the pointer over the line numbers. Click one and the block folds into its first line, with a ⋯ at the end to show that something is hidden; the triangle turns into ▸. Click the triangle or the ⋯ to unfold it again.
Folding only changes what you see. The code is still there and runs exactly as before. If your program stops on a line inside a folded block, at a breakpoint or while you step through a recording, the block unfolds by itself so you can see the line.
From the keyboard, with the cursor on a block's first line (the one with the def, the for or the if): Cmd+Option+[ folds the block and Cmd+Option+] unfolds it on a Mac; elsewhere it's Ctrl+Shift+[ and Ctrl+Shift+]. Ctrl+Alt+[ (Ctrl+Option+[ on a Mac) folds every block in the file at once, and Ctrl+Alt+] unfolds them all.
Finding and replacing#
With the cursor in the editor, press Ctrl/Cmd+F and a search bar opens under the code. Type what you're looking for: every match lights up, and Enter jumps to the next one (Shift+Enter to the previous one). next and previous do the same, and so do F3 or Ctrl/Cmd+G, with Shift to go backwards. Escape or × closes the bar.
Three boxes make the search pickier:
- match case:
Totalno longer findstotal. - by word:
xfinds the variablex, but not thexinsidemaxornext. - regexp: the search text is a regular expression, for the times you know what that is.
The second field is for replacing. Type the new text, then press replace (or Enter in that field) to replace the current match and move on to the next one, or replace all to change every match in the file at once. Ctrl/Cmd+Z takes a replacement back; a replace all comes back in one step.
The search looks through the file that's open in the editor, not the other files of the project. Ctrl/Cmd+F only opens this search bar while you're typing in the editor; anywhere else on the page, it's the browser's own search.
6Running your program#
There is one button that starts your program, Run, and a switch next to it that decides what kind of run it is.
Record off (the switch is grey): Run simply runs your program and shows what it prints. Fast, with no limits. Use this when you just want the result.
Record on (the switch is yellow): Run does the same thing, but writes down everything the program does on the way, so you can walk through it step by step (next section). Slightly slower, and it stops after 5,000 steps, so an accidental endless loop gives you a message rather than running for ever.
You can see which one you are about to get without reading the switch: while Record is on, the Run button itself turns yellow and its play mark becomes a record dot.
What your program prints appears as it is printed. A program that counts to ten slowly shows each line as it arrives, and one that draws shows each shape as it is drawn: you are watching it work, not waiting for it to finish. The page stays yours while it runs: you can keep reading, scrolling and typing.
While a program is running, the Run button becomes Stop, and its play mark becomes a square. Press it and the program stops where it is, even one that would never have ended on its own, and even one sitting in the middle of a long time.sleep(). Nothing is lost: your files stay as they are, and everything the run had worked out is still there for the console to look at.
There is a limit to how much the page will keep: about a million characters. A program that prints without end reaches it, writes ... output truncated, and carries on running; the status line says so, and Stop is the way out.
If your program uses a library such as numpy, matplotlib or pandas, primopy fetches it the first time you use it. The status in the tab row tells you what it's getting (the list can run to a few lines), and then it stays available.
If something goes wrong, the error is shown in red at the end of the output, naming the file and line. For a typing mistake (a syntax error), the editor jumps straight to the line.
Programs written with async and await run too. asyncio.run(main()), asyncio.gather, tasks and asyncio.sleep all work as they do on your own computer, and a recording shows the tasks taking turns: step through it and watch the program switch from one coroutine to the next at each await. The call stack of a task shows only that task, which is exactly what asyncio does. One thing does not work: awaiting something from the browser itself, such as pyfetch. The program stops with a message saying so, rather than waiting for ever.
Running one line at a time#
You don't have to run the whole file. Put the cursor on a line and press Shift+Enter: that line runs, and the cursor moves on to the next one, skipping blank lines and comments. Keep pressing and you walk through the file a line at a time. Select several lines and Shift+Enter runs those.
primopy runs whole statements, so you never cut one in half:
- On a line that starts a block (
for,if,def,while,with,try,class), the whole block runs. - A statement written over several lines, like a long list, runs as a whole wherever the cursor is in it.
- A line inside a function runs on its own. The function's own variables don't exist out here, so a
NameErroris what you'd expect. - Select part of a line, like
x * 2, and you get just its value.
When a line has a value, the way 3 * 7 does in the console, it appears in a small box right under the line. A loop shows one value each time round. An error shows up as a red box under the line that raised it, with the full message in the Output tab. × closes a box, running the same line again replaces it, and changing the line removes it. The boxes are never saved.
Whatever the lines print goes to the Output tab, below what's already there, set off by a thin line (hold the pointer on it to see which lines printed it). Plots and drawings go to their tabs as usual, and input() asks in the Output tab, as in a Run. Stop stops a line that doesn't end, like while True:.
You can also use the mouse. The number of the cursor's line (or of the first selected line) turns into a ▶: click it to run. So clicking a line number once selects that line, and clicking it again runs it. Hold the pointer over the ▶ and the lines it would run light up. While a recording is up, the button is a › instead and takes the tape to that line rather than running anything (see Jumping to a line).
The lines share their variables with the console: x = 5 run from the editor can be looked at in the console, and the other way round. They stay until the next Run, which starts fresh: it forgets them, and clears the boxes and what the lines printed. After that the program's own variables are there to build on, as usual. If you've changed another file that your code imports, the next line you run uses the new version.
Recording a few lines. While Record is on, Shift+Enter and the ▶ record the line or selection instead of just running it; the ▶ turns yellow then, like the Run button. The tape then holds only those lines and opens at their end, showing what they changed, so pressing Shift+Enter line by line works as it does without Record. Start goes back to before they ran, with the variables you had then. While the tape is up, a line's value shows on its Detail steps, like every other value; once the tape goes, the values of the recorded lines stay as boxes under them.
Stopping at a breakpoint#
Click just left of a line number to mark it with a red dot, and a plain Run stops when it gets there. (A Record does not stop: it runs to the end and opens its tape at the dot, where you can step backwards too.) It is not finished, only waiting: the status line says Paused at line 4 in fib(), the editor points at the line, and Variables and Call stack show what the program has in hand at that very moment. Click a function in the call stack to see its variables.
While it waits, the Run button reads Continue and a Stop button appears beside it:
- Continue (or Ctrl/Cmd+Enter) lets the program go on to the next breakpoint, or the end.
- Step ▶, Over ▼ and Out ▲ under the editor move it one line at a time, exactly as they do on a recording. A line that calls a function is one step for Over and a walk inside for Step.
- Stop ends the run where it stands.
The red dots can be changed while the program waits. Click one away and it no longer stops there; click a new one and the next Continue stops at it.
A stopped program can also be talked to. Open the console tab and it offers Attach: from then on what you type runs inside the function the program stopped in, reading and changing its variables, as described in The Python console.
The one place this doesn't work is a page that is not allowed to wait for you, the same setup that makes input() fall back to running the program again; hover the logo to check. There the dots only guide Continue ▶▶ through a recording.
7Stepping through your program#
After a run with Record on, a strip called the tape appears under the editor, together with the step buttons.
The tape#
Each tiny bar is one step of your program. Taller bars mean the program was inside a function (deeper still means a function inside a function). Red bars are errors or breakpoints. A bar with a small notch across its top is a step where you typed into the program from the console; hover it to see what you typed. The yellow line is where you currently are.
Drag along the tape to move through the whole run, like scrubbing through a video.
Jumping to a line#
Put the cursor on a line and its number turns into a ›. Click it, or press Shift+Enter, and the tape jumps to the next time that line runs, counting from where you are: from the start, that is the first time. Press again and it goes to the time after that, and round to the first again after the last: a quick way to watch one line of a loop turn by turn, or one line of a function on each call. A line above the one the tape is on works the other way round, since what you are asking about has already happened: the jump goes to the last time it ran before here, and each further press one time further back. The status line counts along, like Line 6, visit 2 of 3. On a line the program never reached, such as the body of an if that was false, the › is grey and the status line says so.
Nothing runs when you press it, and the recording stays. To run or record a line on its own while a recording is up, first close the recording with Stop or a new Run; then the number is a ▶ again.
The buttons#
| Button | Goes to |
|---|---|
| Start ↻ | The very beginning |
| ◀ Back | One step back |
| ◁ Detail | A smaller step back, inside the line |
| Detail ▷ | A smaller step forward: one piece of the line at a time |
| Step ▶ | One step forward |
| Over ▼ | Forward, but treating a function call as a single step |
| Out ▲ | Forward until the current function has finished |
| Continue ▶▶ | Forward to the next breakpoint, or the end |
The counter next to them reads something like step 24/181 · main.py:6, and inside a line it adds which of the line's small steps you are on, like · detail 3/8.
While a program is stopped at a breakpoint, the four forward buttons drive the program itself rather than a recording, and the others wait until there is a recording to walk. The counter then reads paused · main.py:4 · in fib().
Detail takes a line apart. Press it and the editor lights up the piece Python evaluates next: a name being looked up, a * b being multiplied, a function being called, in the order Python actually applies them. Each piece shows what it came to: in a box under its line, just below the piece, and in a Detail section above Variables, where a list or an object can be opened like any variable. While a recording is up, that section also answers a selection: select an expression in the editor, x * x or sq(4), and its recorded value appears there, with the step it came from (the latest one at or before where you are; if it only ran later, it says later). A function or a class of your own shows as its signature, with its defaults as they were then: function add(item, items=[1]). Select a literal, 0x1F or [1, 2, 3], and its value is read off the text, without running anything. Calls into your own functions are followed inside, and when they come back the call shows what they returned, like f(c) → 7. Where a function leaves, Detail first shows what it hands back, in the same box under the return (or the yield of a generator; a function that runs off its end shows None), and then the rest of the caller's line, so the marker on the tape only ever moves forward, even through a recursion. A return that hands its value straight back is a single step, with those small steps inside it; a separate step marked returns is only there when something ran in between, such as a call from the return line or a recursion, or when the function runs off its end. A few pieces have no value of their own to show, such as x and y, which Python works out by jumping rather than calculating. Step ▶ and ◀ Back skip these small steps, so nothing changes for you unless you ask for the detail.
You can also use the ← and → keys, as long as you're not typing in a text box; with Shift held they take the small Detail steps.
What you see at each step#
Every step shows you the complete state of the program at that moment:
- The editor highlights the line about to run (and switches file if necessary).
- Variables lists every variable with its current value. Anything that changed in the last step gets a yellow marker, the quickest way to understand what a line actually does. A list, a dict, a set or an object of one of your own classes has a ▸ in front: click it to see what it holds, two levels deep, with the first and last few items of a long list. What you open stays open as you step.
- Call stack shows which functions are currently running, the innermost at the top. Click one to see its variables.
- Output shows only what had been printed up to that step, so text appears exactly as you step past the
printthat produced it. - Plots and drawings behave the same way: go back before the line that made them and they disappear again.
Watching an example in a document#
An example in a document may have a Watch button. It records the example and plays it back right under its code, with the same tape and buttons, and the teacher's notes on what to look for appear as the tape reaches their lines. Open takes it to the editor already recorded. The notes are for the code as written: change it, and they go. How to write them is in what to watch in a recording.
8Output, plots and drawings#
The area below the editor has tabs:
- Output: everything your program printed, errors in red.
- Display: pictures your program hands to
display(), one card each. Up to twelve per run. - Plots: charts made with
matplotlib(see example 10) orplotly. Up to twelve per run. A chart drawn at the console withplt.show()comes here too. The tab scrolls down to each new chart, as a terminal does, unless you have scrolled up to look at an earlier one. - Tables: a table to look through, row by row, opened with
View(): a list of rows, a pandas DataFrame, a NumPy array, a DuckDB result and more. - Draw: a canvas your program can draw on, with
turtleor withdrawfrom the built-inprimopymodule.
Where the row is too narrow for every tab, Plots and Tables stay out of it until they have something to show.
Plots with plotly#
A matplotlib chart is drawn as SVG, its lines, marks and letters as shapes, so it stays sharp when you zoom the page, in a document read on another screen and in a saved picture. A chart with very many points (over about 20,000, a big scatter say) would make an SVG of megabytes that the browser is slow to draw, and stays a PNG instead; so does a chart your program is still drawing while it waits, at an input() say. To choose the format yourself, set it in your program before the chart is shown:
import primopy
primopy.plot_format = "png" # or "webp", or "svg" (the default)"png" keeps every chart a PNG, and "webp" makes it a lossless WebP, often smaller than the PNG for a chart of many colours, such as a heatmap or a photo. The setting holds for the rest of the session, console included, until you set it again.
A plotly figure goes to the Plots tab too, among the matplotlib pictures in the order your program showed them, and stays a live chart there: point at it to read the values, drag to zoom, double-click to zoom back out, and use the buttons over its top right corner to pan or save it as a PNG. Install it once with %pip install plotly in the console; a program that imports Plotly Express, plotly.express, gets the numpy and pandas it also wants by itself. There is nothing to set up after that: fig.show() puts the figure on the Plots tab, so does display(fig), and in the console so does a figure left as the line's value, as in a notebook. The chart is drawn by the copy of plotly.js that came with the plotly you installed, so nothing more is fetched for it, and it keeps plotly's own white background in the dark theme, as matplotlib pictures do.
A figure from a cell of a document goes to the Plots tab as well. Update outputs keeps it with the document as a saved figure under its cell, and a notebook's saved plotly figure, as Jupyter writes it, is drawn under its cell as a live chart (see Documents and notebooks).
import plotly.express as px
fig = px.scatter(x=[1, 2, 3, 4], y=[10, 11, 9, 12], title="Four points")
fig.show()Draw#
import turtle works here as it does on a computer: the same commands, the same shapes, the same animation, drawn in the Draw tab instead of a window of its own.
import turtle
turtle.color("red", "yellow")
turtle.begin_fill()
for i in range(36):
turtle.forward(150)
turtle.left(170)
turtle.end_fill()
turtle.done()Three things are different from the desktop. There is no window, so done() and mainloop() return once nothing is left to wait for, and a program that draws and then calls done() simply ends with its drawing on screen; a program that has bound keys, clicks or timers waits for them until bye() is called or you press Stop. exitonclick() waits for a click on the drawing. And image files cannot be turtle shapes or backgrounds, so register_shape("picture.gif") and bgpic() raise an error; polygon shapes, the built-in shapes and compound shapes all work. For the rest, Python's own turtle documentation applies.
draw is the canvas itself, for a program that wants to draw directly:
from primopy import draw
width, height = draw.size()
draw.clear("skyblue")
draw.fill_style = "gold"
draw.fill_circle(width / 2, height / 2, 60)
draw.write(20, 20, "hello", size=24)Quiz: Where things land on the canvas · 3 questionsStart quiz
the canvas coordinates of primopy's draw object: (0, 0), the direction of y, and sizes · first programs; variables, arithmetic and function calls only, no loops yet
- Where on the canvas is the point (0, 0), and which way does y grow?
- What would you change in this program to draw the circle in the bottom-right corner? There is more than one good answer.
- Draw a second, smaller circle so that it just touches the first one from the right. Work it out on the canvas, predicting before each run.
The point (0, 0) is the top-left corner; x grows to the right and y grows downwards (this trips everyone up once). draw is a drawing context, the browser's canvas with Python names: what the canvas documentation calls fillRect is draw.fill_rect here, and fillStyle is draw.fill_style, so anyone who can read those pages can translate them. Styles are set by assignment (draw.fill_style = "gold", draw.line_width = 4), and draw.color(c) sets the fill and the outline colour at once. Every shape call says in its name whether it fills or strokes: fill_rect / stroke_rect and fill_text / stroke_text come from the canvas, and fill_circle / stroke_circle, fill_ellipse / stroke_ellipse, fill_polygon / stroke_polygon, line and write (text) are shortcuts for what the canvas makes you build as a path first; the path calls (begin_path, move_to, line_to, arc, fill, stroke, and the rest) are there too. Angles are in degrees. Drawing calls travel to the page in batches, and time.sleep() and every key or mouse read send what is waiting, so a loop that draws and sleeps needs nothing more; draw.flush() shows the picture right now, for the moment before a long calculation. Colours are the CSS ones, by name, "#rrggbb" code or "rgb(r, g, b)"; a mistyped name gives a friendly error. Beside the keyboard (draw.key(), draw.pressed()) there is the mouse: draw.mouse(), draw.mouse_down() and draw.click(), and on a touch screen a finger is the mouse.
primopy is a module that exists only here, and its draw has its own page with the full reference and more examples: the drawing page.
The canvas is as big as the Draw tab, so make the area taller and run again for a bigger picture. Drawings work with stepping too: record a run and watch the picture build up shape by shape.
Display#
display() comes from IPython.display, and it is how libraries written for Jupyter notebooks show a picture. There is no notebook here, so primopy stands in for one: whatever you display is asked how it draws itself, and the answer appears in this tab.
from IPython.display import display, Image
from PIL import Image as PImage
import io
picture = PImage.new("RGB", (200, 120), "seagreen")
saved = io.BytesIO()
picture.save(saved, format="PNG")
display(Image(saved.getvalue()))Anything that knows how to draw itself arrives as a picture: PNG, JPEG, GIF (an animated one animates), WebP, a matplotlib figure, or plain image bytes. Anything else arrives as the text Python would print for it, so a list or a dictionary still tells you what it was rather than quietly vanishing. HTML from something that has nothing else to say, such as HTML(...), is drawn with the few tags a document's HTML may use, its scripts and styles left out. An object that also prints itself, such as a pandas DataFrame, arrives as its printed text. Markdown(...) is drawn as a document's text, and Latex(...) and Math(...) as formulas, the way a notebook draws them: the maths between $...$, $$...$$ or in \begin{align} is typeset, and the words around it stay words. A SymPy expression arrives as its formula, so display(x**2/2) shows a fraction rather than x**2/2.
There is nothing to install for this, and nothing to write differently. It works whether or not your project uses IPython, and a library that reaches for IPython.display at the top of its own file works too, which is what most of them do. As in a notebook, display() also works without the import, so code copied out of one runs as it is. publish_display_data(), which hands over a bundle of formats rather than an object, shows its first picture, or else its HTML, or else its text. At the console, display() puts its card on this tab too, after the last run's, and the cards of the lines you type add up until the next run, so a turtle made on one line and moved on the next stays one card; a document's cell runs at the console's prompt but is a notebook's cell, so what it displays, and an image left as its last line, is a card, saved under the cell by Update outputs.
Display cards replay when you step, the same as plots: record a run, and each card appears at the moment your program displayed it.
A library that draws its picture once and then redraws it as it goes gets one card, which keeps up with it: each time your program pauses, in time.sleep() or input(), the card shows the drawing as it stands, and when the run ends, the finished one. That is how jupyturtle, the turtle of Think Python, moves its turtle, and jupyturtle comes with primopy, so there is nothing to download or install:
from jupyturtle import make_turtle, forward, left
make_turtle()
for i in range(8):
forward(30)
left(45)The turtle pauses a fifth of a second after each move; make_turtle(delay=0) draws at once. Think Python's own download() of jupyturtle.py works too: it is handed primopy's copy without asking, and the copy it saves in your project is the one used from then on.
Tables#
View() opens a table in the Tables tab. There is nothing to import for it, and a table can be just Python's own lists and dicts:
scores = [{"name": "Ada", "points": 92}, {"name": "Alan", "points": 78},
{"name": "Grace", "points": 88}, {"name": "Linus", "points": None}]
View(scores)
View([s for s in scores if s["points"] and s["points"] > 80]) # only the ones over 80What counts as a table:
- a list (or tuple) of rows, each a dict, a list, a tuple, a namedtuple or a dataclass: the keys or fields name the columns, plain lists are numbered;
- a dict of columns, each a list:
{"name": [...], "points": [...]}; - a pandas or polars DataFrame or Series, and a NumPy array of one or two dimensions;
- a database's table:
View(con, "select ...")orView(con, "people")with asqlite3or DuckDB connection, or a DuckDB result,con.sql("select ..."); and the rows of asqlite3query withcon.row_factory = sqlite3.Row, named by its columns; - a pyarrow Table, and any other library's table that hands itself over as Arrow or through the DataFrame interchange protocol.
import pandas as pd
df = pd.DataFrame(scores)
View(df[df["points"] > 80])Each View() gets a tab of its own, named after what you wrote between the brackets, and the size of the table shows at the right. A column's type stands under its name, the library's own (a dtype for pandas, VARCHAR for DuckDB), and a missing value is shown as its library prints it, None, NaN, NaT, null or NULL, dimmed so that it is not taken for text. Click a column's name to sort by it, ascending, and again for descending; click #, over the row numbers, for the order the table really has. Sorting only changes what you see, never the table. A table of hundreds of thousands of rows opens just as quickly: the rows come from Python as you scroll to them.
A database's result is copied at the View() when that is quick, so it is the table as it was there, and still there after con.close(). One too big or too slow to copy in a moment stays in the database instead: the rows you scroll to are asked for as you get there, sorting is the database's ORDER BY, and what you see is the database as it is then. A sqlite3 cursor is not taken, since it can be read only once and showing it would use it up.
Under Variables, a table can be clicked too, and opens the same way, at a breakpoint from whichever frame you are looking at. A list or a dict still opens to show its items when clicked, and has a small table button beside its type for the Tables tab. Typing at the console to change it updates the view.
View() shows the table as it was at that line: change it afterwards, as scores.append(...) would, and the view keeps what it saw. Record a run and step away from that line, and a yellow strip says so, and takes you back there when clicked. A new Run keeps the old tabs, dimmed, with the rows they had already loaded; close a tab with its ×.
9Programs that ask questions: input()#
Example 8 uses input() to ask the user something. The question appears in the Output tab while the program runs. Type your answer, press Enter, and the program continues. Escape stops it.
The program really does wait for you: it stops at the question, and carries on from exactly there once you press Enter. Nothing before the question happens twice, so programs that use random numbers or the clock behave just as they would anywhere else.
10Working with several files#
The row of tabs above the editor lists the files in your project. At the start there is just main.py. You'll want more files when your program grows (example 9) or when it should read data (examples 12–14).
+(a square with a plus, after the tabs) adds to the project: a file, a folder, or files or a folder from your computer (Files from this computer…, Folder from this computer…, see Files from your computer). Each folder in the projects list has a+of its own, which adds into that folder. Use.pyfor Python code, and.txt,.csvor.jsonfor data. A name liketools/helpers.pyputs the file in a folder, and a name typed without an extension gets.py. Two files cannot have names that differ only in capitals,main.pyandMain.py, since a Mac or Windows takes them for one file (unzipping a download there would write the one over the other), and a file and a folder cannot share a name, asmain.pyandmain.py/x.pywould; nor can a name start with a dot (.env, or.pyalone), since a folder linked to the project leaves such hidden files out. A file that comes in under such a name, from your computer, a ZIP or a link, gets a number instead (Main-2.py), or lands at the top when its folder cannot be. In the dialog, the up and down arrow keys switch between a program, a document, a data file and a folder.- Click a tab to open that file.
- Double-click a tab to rename it. A new name typed without an extension keeps the file's own, so
data.csvrenamedtablebecomestable.csv. - × at the end of a tab closes it; the file stays in the project. Click its name in the project's tree, in the list the project button opens, to open its tab again, at the end of the row; the buttons in its row there rename or delete it. The last tab cannot be closed, so it has no ×.
- Drag a tab along the row with the mouse to put it somewhere else (on a touch screen the row scrolls instead). With the keyboard, Alt+← and Alt+→ on a tab's play mark or its × move it one place. Which tabs are open, and in what order, is kept with the project, and so is where each file's cursor or selection is and how far it is scrolled: a reload, or coming back from another project, finds every file as you left it.
- The play mark at the left of each Python tab says which file Run starts with: a plain grey triangle on the others, a yellow one on the file that runs. Normally the file that runs is simply the Python tab you are on. Click a mark to pin that file, so that Run starts from it whichever tab is open: its triangle is then punched out of a filled yellow coin. Click it again to unpin. The same mark stands beside the file in the project's tree in the projects list, and a click there does the same. Only
.pyfiles can be started. A program in a folder imports the files beside it, as Python does: whenhw3/main.pyruns,import helpersfindshw3/helpers.py, and the files at the project's top can still be imported too.open("data.csv")still means the project's top, wherever the program is, as it would if you startedpython hw3/main.pyfrom there.
Data files are shown in green.
Reading and writing files from your program#
Your program sees the tabs as files in its folder, so this works just as on a normal computer:
with open("list.txt") as f: # reads the tab called list.txt
lines = f.readlines()
with open("out.txt", "w") as f: # creates a new tab called out.txt
f.write("done\n")bread
apples
teaQuiz: Reading a file · 3 questionsStart quiz
reading text files with open() and a with block, readlines() and strip() · a few weeks in; loops and lists are known, nothing about encodings or exceptions
- After the first with block, what exactly is in
lines? - Why is
with open(...) as f:better than plainf = open(...)? - The second block writes out.txt. What happens to out.txt if you run the program twice?
A file your program creates shows up as a new tab marked ◦ and stays for the next run, and that's how example 13 keeps adding to its log. A Markdown, Quarto or notebook file it writes at the top of the project is the exception: that becomes a chapter of the document, not a tab.
Files from your computer#
Files from this computer…, in the dialog of + at the end of the file tabs, lets you pick files from disk and adds them to the project you are in; Folder from this computer…, beside it, picks a folder, which comes in under its own name with the folders in it, without hidden files and what a linked folder leaves out, and no more than 200 files (a phone or a tablet offers no folder to pick, so the choice is greyed there). A folder's + in the projects list adds them into that folder. You can also just drag files onto the editor, which adds them at the top, or onto a folder in the projects list; a folder dragged in keeps its name, as a folder picked does. Either way a dialog shows what comes in before it does: Into folder (the top when empty; type another folder to put everything there), and the files as a tree, each ticked, with its size; untick what you do not want. A file the project already has a file of that name for is marked, with Keep both (the new one gets a number), Replace or Skip, and one choice for all of them when there are several. Each file is shown where it will land: a name a project cannot have is made one (Woche 1 (Intro)/README becomes Woche 1 -Intro-/README.txt), and a file whose name with its folders would be over 64 characters is greyed. Click a file's name to see it under the list as the editor would show it, read-only, beside the project's file of that name. Files that cannot come in (too big, more than 200) are listed greyed, with why, and so is what a folder brought in leaves out, as a linked folder does (hidden files and folders such as .git). A ZIP is unpacked into a folder named after it, data.zip into data/ (or data 2/ when there is a data already), as your computer unpacks one; the dialog can add it as the one .zip file instead, for a program that reads it. What comes in gets no tabs: the editor stays on the file it showed, the status line offers show in the projects list, and there the files are marked just added for a minute, their folders open. Undo takes them out again. A ZIP your program wrote stays packed in the project; Unpack, beside Download on its tab, puts its files in, into the folder named beside it. Dropped on a project that is still its one empty file, a ZIP is unpacked into it, and the project takes the ZIP's name unless you named it yourself; dropped on the project button, it is a new project, as with From files or a ZIP… below. A ZIP that primopy downloaded, brought into a project, makes the dialog ask: open it as a project of its own (as it was, the file that runs and your breakpoints with it), or add its files to this project, in a folder named after it. Where a ZIP is unpacked, one that unpacks to over 512 MB, or one packed in a way the page cannot read (Deflate64, which Windows uses for big files, bzip2, a password) is not, and the status line says why; unpack it on your computer and drag the folder in instead. Files are not uploaded anywhere; they stay in your browser. Very large files (over 25 MB) are refused.
To make a new project of them instead, drop them on the project button, or open the projects list with it and choose From files or a ZIP…: the new project is named after the ZIP or the one file you chose, and holds just what you picked: a table or notes alone are a project too, with no empty program beside them, and Run and Record are greyed until you add a .py file. A ZIP that primopy downloaded brings that project back as it was, the file that runs and your breakpoints with it; any other ZIP gives its files: when they all sit in one folder, as the Mac's Compress and Windows' Send to → Compressed folder pack them, without that folder, as a folder dragged in comes, and without the __MACOSX folder and ._ files a Mac adds beside them. Undo in the new project starts with what you picked; it does not take you back to an empty project. When nothing you picked can go in (every file too big, say, a ZIP that is empty or cannot be read, or R code, which primopy offers to open in Rprimo), no project is made and the list stays as it was; the status line says why.
A file that is not text — an image, a PDF, a zip — comes in too. There is nothing to edit in one, so its tab shows the file itself instead of the editor: images are displayed, a PDF opens in the browser's own viewer (with Print, and Open in a new tab for a phone that shows only its first page, beside Download), sound and video play, everything else gets its name and size, and either way there is a Download button to save it back out. Your program can open() it in binary mode like any other file, and a binary file your program writes turns up as a tab of its own. An SVG file is text, but its tab shows the picture too, drawn on white, and a web page (.html) shows itself; the pencil on the tab puts its source in the editor, and pressed again shows the picture or the page as the source now draws it. Either is drawn live, in a frame of its own: its scripts run, a hover answers and an animation plays, but nothing in it can reach the editor, your projects or anything stored in your browser, and it fetches nothing from the web, so a page that loads a library from elsewhere must carry it inside. An SVG can use only the fonts on your computer: a font it names that is not there is replaced by one of its kind (sans-serif, serif or monospace), not by the browser's serif. Download saves the file as it is. Opened again, the tab shows the picture. Printing such a tab prints the picture, and a web page's tab its source; a PDF prints itself with Print, or with Ctrl+P (Cmd+P on a Mac) while its tab is open. A share link carries these files too: a link holding one is a zip, with the files in it exactly as they are, so a 13 KB workbook makes a link of about 15 KB. Roughly 300 KB of such files fit in one; past that the link is refused and Download in the projects list is the way.
Reading from the web#
Your program can fetch a page or data from an address, with urllib.request, with requests, or by handing the address to pandas.read_csv:
import requests
r = requests.get("https://api.open-meteo.com/v1/forecast?latitude=47.37&longitude=8.54¤t=temperature_2m")
print(r.json()["current"])primopy asks you first: a dialog shows what the program wants to fetch, and nothing goes out until you click Allow. Tick Allow … without asking and that site is let through until you close the page. Nothing of yours goes with the request: no cookies, no sign-in, not even which page asked.
Many sites do not let other web pages read them, and then the browser keeps the answer from your program, whoever asks. The dialog says so, and you can fetch it yourself: Open the address in a window opens it beside primopy; select all of it there, copy it, and paste it into the box (or drag its text, or a file you saved from it, onto the box); look it over, and Hand it over gives it to your program, which carries on with that. A request that sends data, a POST, cannot be opened in a window: the dialog gives you a command to copy instead, nothing to install. On a Mac it runs in Terminal and on Windows in PowerShell, and either puts the answer on the clipboard to paste into the box; on Linux it saves the answer as a file, which you drop onto the box. A phone or tablet has no terminal: there, open the address in a tab, copy it and come back to paste; a POST can only be fetched on a computer, and once its answer is saved to the project there (below), the project answers it on the phone too.
Tick Also save the answer to the project as and the answer becomes a tab, which your program can open() like any other file. With it comes From now on, answer this request from that file, ticked unless you untick it: the request and the file go into web-replies.json, and from then on the program gets the saved answer without asking and without the internet, in a shared copy of the project too. Take the request out of web-replies.json, or delete the file, and it is fetched again. In the projects list, web-replies.json has a globe and says how many saved replies it holds; point at it to see which requests.
A folder on your computer#
In a Chromium browser, which is Chrome, Edge, Brave, Opera and Chromium itself, the editor can work in a folder on your computer directly, the way a desktop editor does. Firefox, Safari and phones cannot hand a page a folder, so there the folder buttons are not shown and everything else works as before.
From a folder…, in the list the project button opens, asks you for a folder. Its files become a new project, named after the folder (the project you were in stays as it was; Undo there starts with the folder's files), and from then on every change you make is written to the folder about half a second after you make it, the same moment it is saved in the browser. A file your program writes lands there too. Left out are hidden files and folders, __pycache__, venv, node_modules, files over 25 MB, and everything past the first 200 files; the status line says what was skipped. Line endings stay as the file had them.
While a project is linked to a folder, a small drive follows its name on the project button, green while it saves there, and the drive over its files in the projects list shows the folder's name. Edit a file with another program, and the editor picks up the change when you come back to the window or press Run: silently if you had not touched that tab, and with a question if you had. Renaming a tab renames the file; closing a tab leaves the file in the folder. Click the folder's name there to stop: the files stay in both places.
A folder belongs to the project it was opened in or saved from: another project has no folder of its own until you give it one, and a project you delete takes its folder link with it until you bring it back with Undo. If you choose a folder that another project already saves to, the editor says so and offers to open that project or to move the folder over to the new one. When a project is open in two tabs, only the tab you can type in writes to the folder; the other shows its name.
The browser forgets its permission when the page closes. On your next visit the drive on the project button turns yellow, the status line offers reconnect, and the drive over its files in the list says Reconnect, in yellow; one click, and the browser asks once whether the page may use the folder again. Until then your files are on screen from the browser's own copy, and nothing you type is lost: it is written to the folder as soon as you reconnect. If you install primopy as an app, the browser can remember the permission for good. If the folder cannot be found any more (moved, renamed, or on a drive that is not plugged in), the drive says Choose again…: pick it where it is now, or another folder. Beside Reconnect and Choose again… is Stop, and the status line that says the folder is out of reach offers stop saving to it: the project then saves to no folder, and the files stay in the browser and in the folder.
Save to a folder…, the drive at the end of the line of Files in the projects list, is the same thing the other way round: the project stays the one you are in, its tabs stay, and you choose a folder for them to land in. Files the folder already has join the tabs. If both sides have a file of the same name with different contents, or one of a name that differs only in capitals (your main.py, the folder's Main.py), a dialog lists them and asks. Keep both, the default, renames your tab, so main.py becomes main-2.py and the folder's main.py comes in beside it. Open as a new project opens the folder as From a folder… does, in a project of its own, and leaves the one you were in as it was. Cancel leaves everything as it was. A file in the folder is never written over by a tab, and the folder's files never replace your tabs.
Nothing is uploaded either way: the folder is on your computer, the page reads and writes it there, and the copy in the browser stays as a fallback.
The project button beside the logo opens the list of projects, with the project you are in showing its files as a tree: folders and files, each with an icon for what it is (a file, a document file, a folder), and each with a box. Run, beside Add over the files, says which file Run starts: The open tab (naming the file that is), which follows the tab you are on, or one file, which runs whichever tab you are on. It chooses what the play mark on a file's tab chooses: the yellow triangle follows the tab, the yellow coin is a file pinned; click a tab's mark to pin its file, and again to let Run follow the tab again. The project's quiz and conversations are listed under the files, with the quiz button's and the tutor button's icons. Click a file's name to open it; a file whose tab you closed gets it back, at the end of the row. A file with no tab stays in the project, and a run that meets it does not give it one. A document file (a Markdown, Quarto, R Markdown or notebook file at the top of the project) never has a tab, since the document shows it: click its name to read it in the document. Its icon is a book, open while the file is a chapter of the document and closed while it is not: click the book to leave the file out of the document, or to take it in again. Under the files come the project's quiz and conversations; a click on the quiz's name opens the quiz, as the quiz button does. The buttons in a file's row rename or delete it, a file with a tab too: the × on a tab only closes it. Rename makes the name a field in its row, the part before the extension chosen to type over: Enter keeps the new name (an extension left off stays as it was), Escape leaves it, and a name that cannot be is said under the files, the field staying. A folder's row has Rename and Delete too: its new name takes everything in it along, and an empty folder goes at once, one with files after asking, with their number. To do the same to several at once, choose them: Select, over the files, puts a box before every row (and reads Done meanwhile), and a click on a name with Ctrl (⌘ on a Mac) chooses one row more, with Shift the rows down to it; from the keyboard, Shift and the arrow keys choose the rows from where you began, Space on a name chooses it while the boxes show, and Escape stops choosing. A folder chosen stands for everything in it. A bar over the files then says how many are chosen, with All, Move to…, Delete (asked once), Download (a ZIP of just those, which opens as files and not as a project), Include and Leave out; dragging one of the chosen rows takes the others along. Each of these is one step for Undo. The tick box says whether the project's download and link take the file; you choose, the editor does not guess which files a program reads. That is why Link to this project and Download sit at the top of the column of tick boxes, with with: under them, on a faint band that runs down it: point at either and the band lights up and what it would leave out fades. A folder's box switches every file below it, and shows a dash when only some are included. Drag a file or a folder onto a folder to move it, or onto the heading to bring it to the top; the four-arrow button (Move to…) does the same, which is what a touch screen and the keyboard use. Which tabs are open, which files are chapters and which are included is saved with the project and is never a change to it: it does not make a download look old. Another project's files open with the arrow beside its name, to read; open that project to change them. A click on one of its files' names, or on its quiz's name, opens that project and then the file or the quiz.
Download, at the top of the column of tick boxes, downloads the files that are included in one archive named after the project, My project.zip say, useful for handing in work, moving to another computer, or keeping a backup. (A project of a single file comes down as that file.) To come back later, drag the zip itself onto the editor and choose Open it as a project, or choose it with From files or a ZIP… in the projects list: the whole project returns, the file that runs and your breakpoints with it, as a project of its own named after the zip, beside the one you are in, which stays as it was. That is what the hidden .primopy.json in the archive is for, and it is the only thing in there you did not write. Unzipping first and dragging the files in works too, and gets you the files without the rest. A project with a history has with its history beside Download, on unless you turn it off: the ZIP then holds the history as the folder .git, which git on a computer reads, and every file of the project, whatever the tick boxes say.
The talks you have had with the tutor are kept with the project and listed under its files, each with a tick box that starts off. Switch one on and Download takes it as a text file in a chats folder of the ZIP, one per conversation, named by the day and by the question it started with, and the link carries the conversation that is open. History lists the project's own talks. Nothing goes back in from a ZIP: a conversation is reopened from History, which is where it lives.
Link to this project copies a link to your clipboard and opens a small panel under the button: Link copied (or, where the browser would not copy it, that you can copy it from the field), the link in a field, already selected (with Copy beside it to try again when the browser would not copy it), and one line on what it carries, such as 2 files and the document. Escape, a click elsewhere or the button again close it; the list stays open. For a moment after a copy the button wears a tick. Paste the link into a message and whoever opens it sees your project exactly as you left it: every tab, the file that runs, the caret where you had it, and your breakpoints. The project travels inside the link itself: nothing is uploaded, so there is nothing to sign up for and nothing to delete afterwards. Very large projects don't fit in a link; use Download for those. A link that lost its end on the way, as a mail or a chat program may do to a long one, opens nothing: the status line says That link could not be read: it may have been cut short, and your own project stays on screen (an example, in a browser that has none yet). Ask for the link again, or for the project as a download. Files your program wrote and you never edited are left out, since running the program makes them again. The packages your project uses travel too, and opening the link installs them there: the project is on screen straight away and the packages arrive a moment later. Opening a link never replaces what is on screen: a link that carries a project opens as a project of its own, and the one you were in stays as it was, in the list behind the button beside the logo. Open the same link again and you are back in that project, with your changes; the status line then says Continuing where you left off and offers Start over, which puts the link's files back after asking (Undo brings yours back while the tab stays open). A link that carries only a document opens as a project of its own too, named after the document, with an empty file beside it for your own code; open the same link again and you are back in that project. A lesson the teacher has fixed on the site is fetched again when you open it, as long as you have not changed that file, and Start over fetches the new one. The link leaves a lesson you have not changed out and names its address instead, which keeps the link short. In a browser that keeps only one project a document is added to it as a file, one chapter more.
11Package management#
A package is Python code someone else has written that your program can import. Python already comes with a great deal of it — math, random, json, datetime, csv — and those need nothing from you: import math simply works. This section is about the rest.
The packages tab, the small icon to the left of the console tab, is where they live. It is quiet most of the time: a lone icon when there is nothing to say, a number once there is something to count, and the word packages in red if something failed.
Most of the time you do nothing#
The several hundred packages that come with primopy's Python — numpy, pandas, matplotlib, scipy, scikit-learn and many more — load when your program imports them. Write import pandas and press Run, and pandas is there before your first line executes. You do not have to ask for it.
Anything else comes from PyPI, the internet's big shelf of Python packages, and that only happens when you ask for it: in the packages tab, with %pip install in the console, or with a line in requirements.txt. An import line alone never downloads anything. Anybody can put a package on PyPI under any name, and import helper, one letter short of your own helpers.py, would otherwise fetch and run a stranger's package called helper.
When your program imports something that is not there, it stops with a ModuleNotFoundError, and the packages tab opens with that package ready to install, one click away. If the name is nearly one of your own files, the package's row says so before you install anything:
Your program imports helper. This project has helpers.py: is that the one you meant?
The packages tab is for the times you want to look, or to decide: to see what your project is actually using, to pick a particular version, to take something out again, or to add a package before you have written the line that imports it.
Adding one#
Type a name into the field at the top and press Install or Enter. As you type, the line underneath tells you what will happen:
- "rich is in this Python already — 14.3.3, no download." It comes with primopy's Python and lands instantly, even with no connection.
- "Not built in. Installing it fetches it from PyPI, once." It is downloaded from the internet the first time and then belongs to your project.
- "PIL comes from a package called pillow. Install pillow." The name you
importis not always the name you install. This is the single most confusing thing about packages, and the field answers it rather than refusing you.
If you cannot think of one, the empty panel offers five to try.
Versions#
Each installed package has a small menu showing which versions can be used here; newest is the default. You can also type a version yourself: cowsay==6.1 for exactly that one, or cowsay<6 for anything older than 6.
If you ask for a version that contradicts the one you have, the panel says so — "This project has cowsay 6.1, which is not <6. Installing this replaces it." — and installing replaces it.
Dependencies#
Packages need other packages. Installing pandas quietly brings numpy, pytz and several more, and none of those are your doing. They are folded away behind the Dependencies button, which tells you how many there are and shows them if you want to look. Each says what pulled it in.
Taking one out#
The bin at the end of a row removes a package. A row that only waits to be installed, with Install on it, has its bin just before that button, and it takes the name off the project's list without fetching the package first. Two things are worth knowing:
- Anything your program has already imported keeps working until Python restarts. A running Python cannot forget a module it has loaded. The row says so and stays on screen until you restart, rather than pretending the package has vanished.
- A package that comes with Python comes back when your program imports it. Removing
pandaswhileimport pandasis still in your code asks for two opposite things, and the run wins. Delete the import first. A package from PyPI stays out once removed, unlessrequirements.txtnames it; the import then stops with aModuleNotFoundError.
Restart#
Restart, at the top right of the panel, starts Python again from scratch: variables, imports and anything half-removed are all cleared. Your packages are fetched back afterwards, so restarting does not cost you the downloads. Your files are untouched — this restarts Python, not primopy.
The list, and requirements.txt#
Your packages are remembered with your project. Reload the page and they are still listed; open the project from a share link and they arrive there too.
Python projects outside primopy usually keep this list in a file called requirements.txt, and if you want one, the button under the list writes it: Write package list into an explicit requirements.txt. It appears as an ordinary tab you can read and edit by hand, one package per line. From then on primopy keeps it up to date. You never need this file to use primopy; it is for handing your project to tools that expect it. If your project already has one — because somebody sent you theirs, or you wrote it yourself — primopy installs from it when you run.
What will not install#
Some packages are written partly in C and have to be compiled for the machine they run on. Nothing compiled runs inside a browser, so those cannot be installed here at all, and the panel says which case it is:
uvloop has to be compiled, and only packages written in pure Python can be installed in a browser. There is no version of it that runs here.
Some packages publish only their source on PyPI and no ready-made wheel, which is the form primopy installs. ColabTurtle is one. When the source is pure Python, primopy builds the wheel itself, in the browser, and installs that; the row says so:
PyPI has no wheel for ColabTurtle, only its source, so it was built here.
Often it is not the package you asked for that has to be compiled but something it asks for in turn. jupyturtle, the turtle for notebooks, lists jupyter among its needs, and jupyter is a whole notebook server with compiled parts under it. primopy then installs the package on its own, fetches each of its needs separately, and keeps what it can:
jupyturtle is here, without jupyter: it has to be compiled, and nothing compiled runs in a browser. jupyturtle works as long as it never actually reaches for it.
The turtle draws without a notebook server, so that is the whole story for it. A package that really does reach for what was left out fails on the import, with the usual ModuleNotFoundError.
Sometimes what a package asks for is here, only not at the version it names. yearfrac asks for a numpy older than 2, and the numpy that runs in the browser is newer. primopy gives it that one anyway, since such a limit is mostly the author being careful, and says so:
yearfrac asks for numpy<2,>=1.14, and the numpy here is 2.4.6, so it was given that one. If something in yearfrac fails, this may be why.
That is a real limit rather than something to work around; the pure-Python world is large, and the several hundred packages that come with primopy's Python include numpy, pandas, matplotlib, scipy and scikit-learn, every one of them compiled, every one of them working, because they were built for this browser in advance.
12The Python console#
The console tab at the right of the file tabs turns the editor into an interactive Python prompt. You type one line, it answers immediately. It's a calculator for trying out ideas without writing a whole program:
>>> 3 * 7
21
>>> round(2.675, 2)
2.67
>>> "hello".upper()
'HELLO'
>>> help(round)- You don't need
print()here; the value is shown automatically. help(something)explains what a function does. Try it on anything you're unsure about.- ↑ / ↓ bring back earlier lines.
- After you've run your program, all its variables are available in the console. Run example 12, then type
itemsto look at the list it made. This is a great way to poke at your results. - While your program is stopped at a breakpoint, the console can step inside it. A bar at the top says where it stopped; press Attach and the prompt changes to the function's name, like
fib() >>>. Nowa + buses theaandbof that function at that moment,print()goes to the console rather than the program's output, anda = 100really changesa: press Continue and the program carries on with the new value. Packages can't be installed while the program waits. Continue or a step lets go again, and the prompt goes back to>>>. Shift+Enter in the editor then runs its line in there too. - Lines run from the editor with Shift+Enter share the console's variables (see Running one line at a time). The console shows a line like
▸ ran main.py:5–6for each; click it to go back to those lines. - A line here gets your files as they are on screen. Change
my_ols.py, then typefrom my_ols import fitand you get thefityou just wrote, without running anything first;open("data.csv")reads the project'sdata.csvas the editor has it, also before your first Run. A file a line writes stays there for the next line. A name you imported before keeps what it was given until you import it again. - Multi-line things like
forloops work: the prompt turns into..., and an empty line finishes the block. - Clear wipes the screen (your variables remain).
%pip install richworks here too, the line you may already know from notebooks. It does the same thing as the packages tab, and what it installs shows up there. A line copied from a README works as it is, quotes and all:%pip install "plotly[express]"installs plotly with its express extra. Options such as-qor--upgradeare for pip, and are left out.- More lines from notebooks work here:
%time sum(xs)runs the statement once and says how long it took;%timeit sum(xs)runs it many times and reports how long one run takes (-n 100fixes the number of loops,-r 3the number of runs);%run main.pyruns a file of your project in the console, so that its variables are there to look at afterwards, with anything after the name insys.argv;%prun sorted(xs)profiles the statement and lists where the time went (-s cumulativesorts differently,-l 10shows only the top lines).%xmodeis accepted and changes nothing, since the tracebacks here already show only your own code.%load_ext autoreload,%autoreload 2and%config ..., the first lines of many notebooks, are accepted without a word: a file of your project that you changed is imported as it is now by the next import line anyway.%load_extwith another module loads it as an IPython extension, as a notebook does. - A first line that begins with
%%makes the command work on the whole cell, as in a notebook. At the prompt, type the lines under it and finish with an empty line; in a document's notebook cell, the cell is all of it.%%timeruns the cell once and says how long it took;%%timeittimes the cell, with anything after%%timeiton its line run before each run as setup;%%writefile data.txtmakes the cell a file of your project (-aadds it to the end of one);%%capture outruns the cell and keeps what it prints inout.stdoutinstead of showing it;%%html,%%markdown,%%latexand%%svgdraw the cell on the Display tab. - A notebook's own helper module can add commands of its own, as Think Python's
thinkpython.pyadds%%expectand%%add_method_to: it registers them with IPython'sregister_cell_magic, and they work here too.get_ipython()answers that code, and the console's own lines, with the parts of a notebook they use: its variables,run_cell,run_line_magic. A library still learns that no notebook is running, so it draws the way it does here. %wholists the console's variables, and%whoslists them with their type and a glimpse of their value (%who listshows only the lists).%resetforgets them all and leaves the screen alone, the opposite of Clear.%historyprints the lines you have typed, oldest first, ready to copy into a file (-n 10for the last ten).%watch total square.xputstotal, andxwhilesquareruns, first in the Variables pane, marked, while you step through a recording or stop at a breakpoint. A global goes by its name, a function's local by the function's name, a dot and its own. A function or a class of your own shows too, as its signature with its defaults as they are at that step, and you need not run again for it:%watch problematic_functionafter a recording showsproblematic_function(item, items=[1])growing step by step. A module, or a function of a library, shows from the next run. Inside a function, a watched global still shows, marked global. You can also watch a piece of the code as it is written,problematic_function.__defaults__[0]: it shows what that piece came to the last time it ran, with the step.%watchalone lists the names,%unwatch xdrops one and%unwatchall of them. The eye at the right of the Variables heading does the same without the console: it opens a field for the names, and a watched row has a × that drops it. The list is not saved and goes in no link: it lasts until you reload the page or open another project.%git status,%git commit -am "…"and other git commands work on the project's history;%git helplists them.- A question mark in front asks what something is, as in R or a notebook:
?math.sqrtshows its type, how to call it and its docstring;?xs.appendand?d["k"]work too. Two question marks,??f, also show the source code, for a function of your own or of a library; where there is none, because the function is written in C, it says so. A?on its own lists what the console answers.
13Code completion#
While typing a name, press Tab (or Ctrl/Cmd+Space) and a list of matching names pops up. Typing a . after a name, like math., opens the list automatically, showing what's available.
Move with ↑ / ↓, accept with Tab or Enter, close with Escape. When available, a one-line description of the chosen item is shown underneath.
Typing ( after a function's name, or a comma between its arguments, shows the function's parameters in a box of their own under the call, the one you are typing now in bold, with a short description of the function beside them, or below them where the line has no room for it, over up to three lines; the names of parameters and the bits of code in it are set in the code's type, as in the parameters. The box comes once you pause typing for a moment, pushing the code below down until it goes again, and follows you while you type the arguments, and goes with the closing ), with Escape, or when you move the cursor yourself; clicking into a call that is already written shows nothing. To see the parameters of the call the cursor is in at any time, press Ctrl+Shift+Space (on a Mac Cmd+Shift+Space works too), in the editor and the console; it shows the box at once.
Completion works out its answers in the same Python that runs your programs, so while a program is running it has to wait its turn. Ask for the list then and it will say so instead of opening; it comes back by itself as soon as the run ends.
14Undo#
Ctrl/Cmd+Z undoes your typing, just like in any text editor, and Ctrl/Cmd+Shift+Z redoes it. Each file remembers its own history, even if you switch between files.
The Undo button in the header goes further: it also takes back things like deleting or renaming a file, replacing your files with an example (where the browser keeps only one project), or clearing your saved work. When the next press would bring files back, the button turns dark blue and says so: Restore 2 files. So if you ever replace your files with an example and see them vanish, the button is already telling you the way back. An example opened from the menu is a project of its own and replaces nothing: yours is in the list behind the button beside the logo. Hover it to see exactly what the next press will undo.
Adding a chapter to the document, editing it, updating its outputs and closing it are steps like those for any file: the document is files of your project. The only thing that can't be undone is a file that your own program overwrote. Moving a file or a folder in the list of projects is a step like renaming one; the boxes there (Run's choice, the tick boxes, a document file's chapter), like which tabs are open, are how the project is looked at, not what it holds, so Undo leaves them as you set them.
Bringing back a version or a file from the project's history is a step too. A switch to another branch, a merge and a stopped merge are not, and they empty the list, since an Undo of their files alone would leave the history somewhere else; their way back is the history's own.
Undo belongs to the tab you are in. When another tab takes over the project (see Is my work saved?), this tab's Undo history is cleared, and a tab that only shows the project has nothing to undo. Going to another project and back keeps the steps of the project you left, as long as no other tab changed it meanwhile.
A file you delete outlasts that history: the project keeps it for a day, so a reload, a closed tab or another tab taking over does not lose it. Once the button has nothing else left to undo, it reads Restore 1 file and brings back the files deleted lately whose names are still free. It keeps the last ten, up to 1 MB in all; a larger file comes back only while the tab you deleted it in stays open.
15The tutor#
Tutor opens a chat with an AI tutor in the bottom right. It's set up to teach rather than to hand over answers: expect questions back, hints, and nudges in the right direction. It's a good place to ask "why is this wrong?" or "what does this line do?"
It is a language model, not an oracle. Ask the same thing twice and the wording will differ; sometimes it will answer straight out instead of asking back, and sometimes it will simply be wrong. When what it says and what your program does disagree, your program is right. Run it and step through it.
Type your question and press Enter (Shift+Enter for a new line). While the tutor is answering, Ask turns into Stop.
Two checkboxes under the input:
- send my code (on by default): sends the tutor the file you're editing, where your cursor is, your last output or error, the last few lines you typed in the console with what they printed, and, if you're paused in a step, the current line and its variables. With this on, "why is this wrong?" is a complete question.
- thinking: lets you see the tutor's reasoning, shown dimmed above its answer.
Link to this project also carries the conversation that is open, once you have ticked its box in the list: a way to show someone what you asked and what came back, without a screenshot. Only what was said travels: nothing is uploaded, but do read the conversation before you send the link on, the same as you would a screenshot.
New starts a fresh conversation, and History brings back an earlier one of this project, since conversations are kept with the project they were had in: nothing you asked is thrown away when you start again. Download in the projects list takes the conversations you have switched on, as text files. Quiz, between them, is for a project that comes with questions; that is section 16. Your tutor messages are the one thing that leaves your browser; they go to the tutor server, where they are used to write the answer and then dropped. Nothing you type is filed away, no record of how you are doing follows you from one day to the next, and nothing you ask is passed to your teacher. Everything else stays on your computer.
The tutor needs the page to be served from a web server; it doesn't work if you opened the page as a file from your disk.
A link can also carry a quiz for the tutor to ask you about the project. That is the next section.
16Quizzes#
A quiz is a set of questions a teacher has written about a project, and a link carries it the same way it carries the files. Open such a link and the tutor's pane opens with the quiz waiting in it: Start quiz, beside + New at the top of the pane, lit gold until you press it. Nothing is asked until you do. The tutor knows the questions, and where the teacher wrote one, it knows the reference answer too.
Press it and the first question is there in the conversation, where your answer goes under it. Answer in your own words in the chat. The tutor sees only what you type there: in a quiz it never gets your code, and the send my code box is not shown, so write your answer, code included, in the chat. It helps you along rather than marking you: it says whether you are close, gives a hint when you ask for one, and keeps the reference answer to itself until you press I'm done, check my answer, when it compares what you said with what the teacher wrote, or I give up, show me the answer. Some questions are meant to be worked out rather than answered, and for those the tutor is meant to give you the next step instead of the finished thing, even when you give up. Nothing is scored and nothing is reported to anyone: the quiz is for you.
One question at a time. Next question → appears above the box once the tutor finds your answer right or nearly so, or once you have said you are done with the question or given it up. Its reply then has a green edge where your answer holds, and a yellow one where something is still missing; that colour is all there is of a mark, and it stays on your screen. Beside the question you are on, ‹ Back goes to the one before and Skip › to the one after, so a question you are stuck on never holds you; one you went past without a word is not left behind in the conversation. The questions stay in the conversation as you go, with your answers between them, to scroll back through. On the last question, once you are done with it, Finish: how did I do? asks the tutor to sum up: what held up, and what to go back to.
Some quizzes have no fixed questions at all, only a topic and a level. The tutor then makes them up as it goes, one per turn, and asks the first as soon as you start; Next question → asks for the next, once you are done with the one you have, and Skip › asks for it at any time.
Taking a quiz is a conversation like any other, so it is left the way any conversation is left: + New starts an ordinary one, and History keeps the quiz, marked there with the quiz's own icon. Open it there and you are back in the quiz where you left off, as long as the project still holds the same questions; if it no longer does, the conversation is still there to read, but not to go on with: the box under it is shut, because an answer typed there would be about the project you have now. + New opens one you can ask in. Restart quiz — the same button, while you are in one — begins again at the first question, and what you did before stays in History. An example from the menu or another link opens a project of its own, and the quiz stays with the project it came with: go back to that project and it is there, with its conversation. Replacing the files here with an example takes the quiz away with them, and the run you were in stays on the pane the same way: readable, and closed to further questions. A quiz survives a reload. A link that carries files and a quiz opens as a project of its own, so your previous project is still in the list, quiz and all.
Try one here. This quiz has no files of its own, so the editor opens with an empty main.py to try things in:
Quiz: Loops, one at a time · the tutor asksStart quiz
for loops over range() and over lists; while loops · first weeks of Python, before functions; no comprehensions
Writing a quiz#
Anybody can write a quiz and share it with others. The pencil beside the quiz button, at the top of the tutor's pane, opens a sheet over the pane where you write the quiz as plain text, one line per thing. The editor stays beside it, so you can look at the code you are asking about while you write the questions:
Title: Reading a file
Topic: reading text files with open() and a with block
Depth: second week; open(), readlines(), strip(); nothing about encodings
Note: Insist on the with block. Question 3 is to be worked out with the student; never hand over the finished loop.
Q: What does f.readlines() give you, exactly?
A: A list with one string per line, each still ending in its newline character (except possibly the last).
Hint: Print it and look at the quotes.
Q: Why is `with open(...) as f:` better than `f = open(...)`?
Q: Write a loop that prints only the lines longer than five characters, without the trailing newline. Work it out step by step.- Title, Topic, Depth and Note each take a line, or several: a line without a key continues the one above it. A key stands at the very start of its line; an indented one, such as an option
a: (1, 2)or a linetitle: strof code, is part of the text it stands in. - Each Q: is a question. An A: under it is the reference answer, and a Hint: is what the tutor should say first when asked for one. Both are optional: without a reference the tutor assesses with what it knows, and a question with several good answers is treated as one.
- A question can run over several lines, so it can be a piece of code with gaps in it: write
for i in ____(10):and the blanks are what the student supplies. Mark a gap however you like. The code around it is given, and the tutor neither fills a gap in early nor rewrites the lines you wrote. - Topic and Depth are in your own words: what the questions are about, and what the student can be assumed to know or must not be asked for. Depth is a ceiling as well as a floor: "before functions" means the tutor will neither ask for one nor explain with one. Depth can also say which way the student learns: "theory first" has the tutor go from the rule to an example, in its questions, hints and explanations alike, and "applied" or "from examples" from an example to the rule.
- Note is for the tutor alone: the class, what to insist on, which questions are to be worked out rather than answered.
- Code: is still read, but a run of a quiz sends the tutor none of the student's code whatever it says, and hides the send my code box: the tutor sees only what the student types. It is a line of its own: anything on the lines after it, until the next key, is the note.
- A question can carry a rubric for the tutor, under its Q: and only where it helps; a run of the quiz shows the student none of it, any more than the A:, while the quiz sheet shows it, like the A:, to whoever opens the quiz to edit it. Hint: may stand several times, each line a step of the ladder of hints, first to last. Core: is one point the answer has to make, a line each, where the answer has parts or must use a term; without one, the A: is the one point. A term the answer has to use goes in backticks, as in
Core: the error is a `KeyError`, and a Hint: under a Core: is a hint for that point. Check:, once a question, is a check of the answer that can be run:Check: value [2, 5, 8]compares the value written, without running anything;Check: expr xs[-1] given xs = [3, 1, 4]evaluates the student's expression after the code after given (statements separated by;, and given is optional), and an answer that only writes out the value, or uses none of the names given, is left to the tutor to read rather than taken as right;Check: output "a 1\nb 2" given d = {'a': 1, 'b': 2}runs their code and compares what it prints with the text in quotes. Accept: lists phrasings that count as the answer, separated by|, and Work: yes marks a question to be worked out in steps. The editor keeps these lines with the quiz and carries them in its links. A quiz with any of them is taken by the quiz tutor: the editor keeps each question's state and decides the verdict itself, so that a point once made stays made, while a model only reads which points an answer makes and words a short reply, passing on the hints in the student's language, and no reply is shown before it has been checked for giving away a point still open. The Check: runs in the editor's own Python, in names of its own, so it neither sees nor changes what the console holds. A quiz without these lines goes to the tutor as before. - A quiz with only a Topic and a Depth is complete. The tutor then asks its own questions.
Return keeps the quiz with the project; there is nothing else to press, and Esc does the same. The button at the top of the pane then reads Start quiz, a reload keeps it, and every link made from the project carries it — including a link you make while the sheet is still open, which carries what is on the sheet at that moment. Editing a quiz you are in the middle of taking changes the questions without ending the conversation.
The sheet is silent while what you have written can be a quiz, and says what is wrong when it cannot: returning then leaves the sheet where it is, with the reason beside the button, and a link waits until the quiz is finished. Remove, beside the sheet's name, takes the quiz out of the project again, and so does emptying the box; it is also the way out of writing you have decided against, finished or not. Undo puts back the quiz you had before writing, editing or removing.
Note the link is the whole quiz, reference answers included: anyone who can read a link can read them, so a reference answer is there to help the student check themselves, not to be kept from them.
17Documents and notebooks#
A link, or a Markdown file, Jupyter notebook or Quarto file you drop on the editor, can open as a document: text to read on a tab of its own, in place of the editor, with examples you run where they stand with Run here. The cells share their names with the console, a cell first runs the ones above it that have not run yet, and the document is files among yours: the Markdown, Quarto, R Markdown and notebook files at the top of your project are its chapters, and the files it brings become tabs like any other. The chapter files themselves have no tab of their own: the document's tab shows them, and the project's tree in the projects list lists them. Teachers write documents in Markdown and hand them out as a link.
A document can also hold exercises: code to finish, often a function whose body is just ..., with a Check button that tries what you wrote and says how many of its checks pass, and what the first one that fails expects (exercises with a check). And an example with a Watch button plays its recording with notes, as in section 7.
All of it is on its own page: documents and notebooks, which you can also open in the editor as a document and try it out there.
18Is my work saved?#
Yes, automatically, in your browser, about half a second after every change. Reopen the page and everything is as you left it: all files (the document's among them, and where you were reading it), breakpoints, console history and the recent tutor conversation. You'll see Your files are back. There is no need to press Ctrl/Cmd+S, but it does no harm: it saves at once and says Saved. The theme and the sizes of the areas are kept too, but for the browser rather than for the project: they are the same whichever project you open.
Seven things to keep in mind:
- It's saved in this browser on this computer. Another browser or another computer starts empty. To move work, use Download in the projects list (the document comes with the files; From files or a ZIP… brings the ZIP back elsewhere), or, in a Chromium browser, keep the project in a folder on your computer.
- What is kept somewhere else. The projects list says, under the project's files, whether your work also exists outside this browser: Downloaded copy is up to date or Changed since you downloaded it after Download, the same for a link you copied, Also in folder … when a folder follows the project, and Only in this browser when none of them does. The same line stands beside each project in the list, and the list's footer says how much room the browser gives this site. A download or a link that leaves out a file whose tick you took off does not count as a copy. It is a reminder and never a warning for work you have downloaded or kept in a folder. The browser is asked to keep this site's storage at your first change (some show a question; if you decline, it is not asked again for a week), because a browser that is short of room may otherwise clear a site's data; Safari clears it after a week without a visit.
- Your projects. The browser keeps every project you start: a new one, each example you open, each link that carries a project, a copy. The button beside the logo names the one you are in and opens the list of them under it, newest first, with when each last changed (the day and the time) and how big it is; the same button closes the list again. Click a project to open it, or start one: New project (empty), From files or a ZIP…, From git… (a repository on a git server, see A history of versions) or, in Chromium browsers, From a folder…. Where the browser keeps only one project, the button opens that one, with its link, Download and folder. The project you are in has Rename (a pencil) and Delete at the end of its row. Over its files sit Add, the
+at the end of the tabs (the list stays open, and what it adds shows among the files; a new file's name such asdata/a.csvmakes the folderdatatoo), Select, to choose several files and folders, and Run; at the end of the line of Files, in Chromium browsers, its folder: the drive (Save to a folder…), or the drive with the linked folder's name (click it to stop) or with Reconnect; its link (the chain link) and, below it, Download (a ZIP) sit over its files' tick boxes. Where the list is wide enough, as on a computer, these buttons say their names beside their icons (Add, Select, Save to a folder, Permalink, Download); on a phone, the icons alone. Another project shows its buttons once its files are open with the arrow beside its name: Rename and Delete in its row, its link and Download over its files; its link carries what is saved of it, as its Download does, with the file that was open and its cursor or selection. Rename makes the name a field: what you type there is the project's new name once you press Enter, click elsewhere or press Rename again; Escape brings back the old one. Two projects never share a name: a name another project has (in any mix of capitals) is refused and the field says so; a second example, copy or link of the same name gets a number (Hello 2). An example you open and leave as it came (nothing typed, added, renamed, installed or removed, or asked of the tutor) is not kept: it goes when you open another project, and the menu brings it back as it was. A deleted project keeps its row for a day, with Undo: after a reload, after closing the tab, and in your other tabs too, and only then is it gone for good. Until then its files still count towards what the browser keeps, so a line under the list says how many deleted projects are kept, with Empty the trash, which removes them for good at once; when the browser is out of room, the status line offers Empty the trash too, and saves again in the room it frees. A project that took its name meanwhile leaves it the name with a number; if its folder was linked to another project in the meantime, Undo asks whether to take the folder back (the other project then has none) or to bring the project back without it. Each tab works on one project at a time, and a new tab opens the most recent one no other tab has open. - One tab at a time writes a project. When a tab opens a project another tab has open, it shows it read-only, and follows it as you type in the other: a bar under the header says Open in another tab · read-only. Run, editing and the other buttons that change the project are off there. Press Edit here and the other tab saves and hands over, and becomes the read-only one; Make a copy makes a project of its own from what the tab shows. This is what stops two tabs from saving over each other. A tab opened while every project is open elsewhere shows the most recent one read-only, with the list over it. A link that carries a project, opened in a read-only tab, opens as a project of its own and the tab goes to it; a link that carries only a document does the same. If a tab holds changes it could not save, because another tab (or an older copy of the page) saved over them or the project was deleted, the bar says so and the changes stay on screen: Make a copy with them keeps them as a project of their own, Download my files keeps a copy on your computer, and the browser asks before such a tab is closed. In a browser that keeps only one project there is no copy to make, and Keep mine saves them over the other tab's instead.
- Large files are fine, and closing a tab loses nothing. Your files are kept as separate records in the browser's database, so a project can hold files of up to 25 MB each (a plot a program saved, a data file) and a save only writes what changed. A file your program writes is saved the moment it is written. If you close a tab in the middle of typing, what it had not yet saved is kept aside and put back the next time the project opens. In a browser that has no database to offer (or on a page that only lends storage), the project is kept as before in one piece, and files over 400 KB are refused.
- Some browser setups block saving, for instance a private window that allows no storage, the page opened directly from a file, or inside another site. The status line then says This browser cannot save your work: it goes when the tab closes, with Download files, and the logo says files not saved when you hover it (where saving works it says files saved in this browser). Use Download files before closing the page.
- A save that fails says so. If the browser refuses a save, because it is out of room, because its storage stopped answering (Safari does this now and then, and the page first opens the storage again and tries once more), or, in a browser that keeps the project in one piece, because the project has grown too large for that piece, the status line says Not saved (or This browser is out of room for your files) with Download files, and the logo says files not saved. Your files stay on screen as they are. The page tries again at your next change and every 15 seconds, and once a save goes in the status line says Your files are saved again.
Nothing you write is sent anywhere, apart from messages to the tutor.
A history of versions#
A project can keep a history: versions of its files that you choose to keep, each with a line saying what changed, and any of them can come back. It is git, the tool programmers keep their work in, running in your browser, so what you learn here works the same way on a computer.
Git, at the end of the line of Files in the projects list, beside the folder's drive, opens it. The first time it says No history yet. Type who you are, Name and Email (any address: it is written into each version and need not exist; both are kept in this browser), and press Start a history: the files as they are now become the first version, called Start of the history unless you type other words.
Such a version is a commit: the files of the project at that moment, with your message, your name and the time. From then on the dialog lists under Changes each file that differs from the last commit, new, changed or deleted. Click a name to see what changed: the last commit on the left, now on the right, the changed lines marked, and long stretches without a change folded into one line that opens with a click. Type what you did into What did you change? and press Commit: every change goes into one commit. Nothing is ever committed by itself; you decide when a version is worth keeping. A commit whenever something works, with a message that says what you did ("read the list from list.txt", "fix the average of an empty list"), makes a history you can find your way back in.
Under Commits they stand newest first, fifty at a time, with Show more. Click one to see the files it changed, and a file to see what changed in it. Bring this version back makes the files as they were in that commit, and Bring this file back does it for one file. Neither changes the history: the files change, as one step for Undo, the Changes list shows it, and a commit keeps it if that is what you want, with Back to: … proposed as its message. A file the history does not know, one you never committed, stays as it is. Where files have changes that are in no commit, the dialog asks first: Commit them first, Replace them, or Cancel.
Branches. A branch is a line of commits of its own, for trying something out without touching what works. New branch… makes one at the last commit and goes on to it; the files stay as they are. The select over Changes lists the branches: choose one and press Switch, and the files become those of that branch's last commit (files with changes in no commit are asked about first, and files the history does not know stay where they are). Merge… brings another branch's commits into the one you are on. Where both branches changed the same lines, git cannot choose, and the dialog lists those files under Merging idea: 1 file needs your decision. For each, Keep this branch's or Take idea's takes one side; or open the file, where git has put both versions between lines starting <<<<<<< and >>>>>>>, keep what should stay, delete the marker lines, and come back. Commit the merge is refused while markers stand, and Stop the merge puts the files and the history back as they were before it. A switch, a merge and a stopped merge have no Undo, and they empty the Undo list: their way back is git's, which the dialog says (Switching back to main takes you back).
Leave files out of the history… opens .gitignore, a file of patterns for git to leave out, made with a few lines on how it is written where the project has none: data.csv for that file, *.log for every file ending in .log, output/ for a folder and everything in it. Commit and %git add then pass those files by. .gitignore is the one name starting with a dot that a file of yours can have.
Where the history is kept. In this browser, beside the project, as the project's files are. The foot of the dialog says how big it is, and Delete the history… removes it, after asking, for good; the files stay. Download in the projects list takes it along: beside it, with its history (on unless you turn it off) puts the history in the ZIP as the folder .git, which git on a computer reads as it is (git log, git status), and with it every file of the project, whatever the tick boxes say, since a history whose files were missing would show them as deleted. That ZIP opened with From files or a ZIP… is the project again, its history with it. A ZIP of a repository from elsewhere, opened with From files or a ZIP…, brings its history too, as long as every file of its last commit has a name a project can have (LICENSE or Makefile, without an ending, cannot) and fits a project (no file over 25 MB, no more than 200 files), it holds no submodules or symbolic links, its .git folder holds less than 100 MB and 20 000 files, and no branch's last commit holds a name no repository may hold (a .git folder, a backslash); otherwise the files come in without it, and the status line and the Git dialog say why. Branches and tags whose names a history here cannot have (Main beside main, a name starting with -) are left out of it, and the status line names them. One with a Markdown file or a notebook at its top opens as a document instead, and its history is left out, which the status line says. A version or a branch that would bring a file over 25 MB or more than 200 files into the project is refused, by name. Text files that come with Windows line ends (or a byte-order mark) show as changed at once, since the editor keeps text its own way, and the dialog proposes one commit for them, Line endings as the editor keeps them. A copy of a project and a link carry no history. A folder on your computer linked to the project gets the files and not the history: a .git folder in it is another repository, your computer's, which the editor neither reads nor writes. The folder holds the branch you are on, as a working copy of git on a computer does: a switch takes the files only the other branch has out of the folder and writes them back when you switch back, and a file you changed in the folder with another program stays there.
A tab that only shows the project (see above) shows its history too, and changes nothing in it.
A git server. A history can also live on a git server, as programmers keep theirs: a school's or a teacher's (Gitea, Forgejo, or git behind a web server). primopy talks to it straight from your browser, so it works only with a server that allows requests from other websites (CORS switched on, as the paragraph for a teacher below says); github.com, gitlab.com and most public hosts have it off, and primopy says so instead of trying. Before anything goes to a server, a small question names it: Allow, Do not allow, or allow it until the page is closed. Nothing ever reaches a server you did not allow, and nothing is asked of a server by itself: only when you press a button or type a command for it.
- A repository as a new project.
%git clone <address>in the console opens a dialog with the repository's address, as the server's page shows it for cloning (it often ends in.git), and Get it as a new project makes a project of it, named after the address (…/course.gitbecomes course), with its files, its history and its server. It takes the server's default branch only (the one its page shows first). While it runs the dialog says how much has come, with Stop; stopped, closed or left for another project, it makes no project. A repository with a file a project cannot hold (a name without an ending such asLICENSE, a submodule, a file over 25 MB, more than 200 files) makes no project, and the dialog names the files. An empty repository makes a project with an empty program file and the server kept: commit your files, then Send puts the first commit there. - The Server row in the Git dialog, under the branch, names the history's server, or offers Connect to a server…, which asks for the address and keeps it only if the server answers. Beside it stand how many of your commits are not on the server yet and how many on the server are not here yet, as of the last time the server answered. Get changes fetches the server's commits of the branch you are on and merges them into it; files with changes in no commit are asked about first, as for a switch, and where the server's changes and yours meet in the same lines you decide as in a merge, with Keep yours and Take the server's version. Send sends your commits on the branch you are on; when the server has commits that are not here, it says to get them first, and changes in no commit stay here. Change… gives the history another address or Removes the server; the files and the commits stay. Get changes and Send are off on no branch, during a merge and in a tab that only shows the project, and say why. A send that was interrupted says that it may or may not have reached the server: Get changes shows which.
- Signing in. A server that wants a name asks for one: Name and Password or access token (an account with two-step sign-in needs an access token, made in the server's settings, in place of the password). primopy keeps it only until the page is closed or reloaded, and only to send it to that server: never stored, never in a ZIP, a link, the console's history or the history's record of its server. An address typed with a password in it (
https://ada:secret@…) works the same way, and the password is taken out of the line before the console shows or keeps it (put such an address in quotes if its password holds a blank and an@). On anhttp://address the dialog warns that the password crosses the network as it is typed. The name goes to every project's requests to that server during the visit; the Server row says Signed in as …, and Sign out in Change… forgets it at once. - In the console
%git remote add origin <address>,%git fetch,%git pulland%git pushdo the same with git's words. The address a ZIP's history came with is never reached: type it again with Connect to a server….
For a teacher: a server that works with primopy. The editor's requests come from a sandboxed frame, so the server sees them with Origin: null. On the repository's info/refs, git-upload-pack and git-receive-pack the server must answer with Access-Control-Allow-Origin: * (or null) and Access-Control-Allow-Headers: Authorization, Content-Type, and answer OPTIONS there with the same headers; Access-Control-Allow-Headers: * does not cover Authorization. In Gitea, [repository] ACCESS_CONTROL_ALLOW_ORIGIN = * in app.ini is meant to give its git routes those headers, and by its code Forgejo's setting is meant to do the same; nginx or Apache in front of git http-backend need the two headers and the answer to OPTIONS. Serve it over https: by the browsers' own documentation, a browser asks before a page on the internet reaches an address in the school's network, and an http:// server there is refused by Firefox, very likely by Safari, and reached by Chrome only after that question. Make the repository without a licence file, or name it LICENSE.md, since a project's files need an ending. GitLab has no such setting for its git routes and needs a proxy in front; github.com and gitlab.com cannot be reached at all. What has been tried: git http-backend behind the small server of the editor's own tests, on the same computer, over http, in Chromium. Gitea, Forgejo, GitLab, a server elsewhere in a network, https, the browser's question about the local network, Firefox and Safari have not been tried yet.
In the console, %git and a git command work on the same history, for those who know git or want to learn its commands. %git help lists them:
%git status what changed since the last commit
%git log [-n 5] [-p] the commits, newest first
%git diff [--cached] what changed, line by line
%git show [<commit>] a commit, and what it changed
%git init a history for this project
%git add <file>… | . | -A | -u files staged for the next commit
%git commit -m "…" | -am "…" a commit of what is staged (with -a, of every change to a tracked file)
%git branch [<name> | -d <name>] the branches; a new one here; one deleted that is merged
%git switch <branch> | -c <name> to a branch; or a new one here, and to it
%git checkout <commit> the files of an earlier commit, on no branch
%git merge <branch> | --abort another branch's commits into this one; or the merge stopped
%git restore <file>… | . [--source <commit>] files as in the last commit (or another), and what was staged for them dropped
%git reset --hard every tracked file as in the last commit; Undo takes it back
%git tag [<name>] the tags; or a new one on the last commit
%git config user.name "…" | user.email … who commits, kept in this browser
%git remote [-v] | add origin <address> | remove origin the server of this history
%git ls-remote the server's branches and tags
%git fetch [origin <branch>] the server's commits of a branch into origin/<branch>; the files stay
%git pull fetch, then merge the server's commits into the branch you are on
%git push [-u origin <branch>] the branch you are on, to the server
%git clone <address> a server's repository as a new project, in a dialog of its own
%git blame, describe, rev-parse, rev-list, cat-file, ls-files, for-each-ref: as in gitA command that would drop commits for good, a reset to an older commit or a rebase, is refused, and so are stash and commit --amend; rm and mv are done in the project itself (delete or rename the file, then commit). There is no editor to write a message in, so a commit takes it with -m. Git answers in English, as it does on a computer. %git push sends only the branch you are on, never with --force, and %git clone opens From git… with the address filled in, asking the server nothing until you press its button. A %git line in a document's cell is not run there: %git works in the console.
19Changing the layout and theme#
Every boundary between two areas can be dragged: the sidebar's width, the height of the tape, the console, the call stack, and the tutor. On a narrow screen the areas stack on top of each other instead.
The ◐ button at the right of the header switches the look: it steps from auto (follow your system) to light (☀) to dark (☾).
20Keyboard shortcuts#
Anywhere#
| Key | Action |
|---|---|
| Ctrl/Cmd+Enter | Run (recording, if Record is on); Continue, while stopped at a breakpoint |
| ← / → | Step back / forward (when not typing) |
| Shift+← / Shift+→ | A smaller step back / forward, inside the line |
| Ctrl/Cmd+Z | Undo |
| Ctrl/Cmd+S | Save now, to the folder too if the project has one; the status line says Saved (the browser's own Save Page As would keep the web page, not your code) |
| Alt+← / Alt+→ on a file tab's play mark or × | Move the tab one place along the row |
Editor#
| Key | Action |
|---|---|
| Tab | Indent, or complete the name being typed |
| Shift+Tab | Un-indent |
| Enter | New line at the same indentation |
| Shift+Enter | Run the line the cursor is on, or the selected lines (record them while Record is on); while a recording is up, take the tape to that line, and to its next visit on each further press |
| Ctrl/Cmd+Space | Open the completion list |
| Ctrl+Shift+Space (Mac also Cmd+Shift+Space) | Show the parameters of the call the cursor is in |
| Ctrl/Cmd+F | Find and replace in this file |
| Enter / Shift+Enter in the search field | Next / previous match |
| F3 or Ctrl/Cmd+G | Next match (with Shift: previous) |
| Escape | Close the search bar |
| Cmd+Option+[ / ] (Mac), Ctrl+Shift+[ / ] | Fold / unfold the block that starts on the cursor's line |
| Ctrl+Alt+[ / ] (Mac: Ctrl+Option) | Fold / unfold every block in the file |
Console#
| Key | Action |
|---|---|
| Enter | Run the line |
| Shift+Enter | Add a line without running |
| ↑ / ↓ | Earlier lines |
| Tab | Complete |
| Ctrl+Shift+Space (Mac also Cmd+Shift+Space) | Show the parameters of the call the cursor is in |
| Escape | Abandon an unfinished block |
Tutor#
| Key | Action |
|---|---|
| Enter | Send |
| Shift+Enter | New line |
Guided tour#
| Key | Action |
|---|---|
| Enter or → | Next stop (after Back too) |
| ← | The stop before |
| Escape | End the tour |
21Things primopy can't do#
- Recording stops after 5,000 steps. For long-running programs switch Record off.
- The Variables box shows at most 26 variables, and long values are shortened. Large
numpyarrays andpandastables are summarised by their size rather than shown in full. - The internet only with your yes. A program's request waits until you allow it, and a site that does not let other web pages read it has to be fetched by hand; see Reading from the web.
- No windows or graphical programs beyond plots and the Draw canvas, which is also where
turtledraws.tkinterandpygameare not available. - Everything lives in one browser. Use Download in the projects list to move work elsewhere, or a folder on your computer in a Chromium browser such as Chrome, Edge, Brave or Opera.
- The tutor can be wrong. It is a language model: its answers are not fixed, and it can be mistaken about your code. Check what it tells you by running the program.
22When something goes wrong#
It never gets past "Downloading Python". Python is fetched from the internet the first time. Check your connection and reload.
My files are gone after reloading. Saving is blocked in this browser setup; hover the logo to check. Ask whoever gave you the page for a proper web address, and use Download in the projects list in the meantime.
open("data.txt") says FileNotFoundError. The name must match a tab exactly, capital letters and folder names included.
import helpers doesn't work. The file must be called helpers.py, and you write import helpers without the .py. For a folder, it needs a file called __init__.py inside (see example 11). A program in a folder finds the files beside it first, then those at the project's top: hw3/main.py imports hw3/helpers.py as helpers, but main.py at the top imports it as hw3.helpers.
The tutor says it can't reach the server. The page has to be opened from a web address, not from a file on your disk.
My program is stuck, or prints for ever. Press Stop; while a program runs, that is what the Run button becomes. An endless loop stops there and then, with your files and everything the run had built up untouched; there is no need to reload the page. With Record on, a run also stops itself after 5,000 steps.