← Reference

Dashboards and live data: cheat sheet

Data detective · In any playground, open Reference to copy these.

square (loop)

Draw a square by repeating forward and right four times.

for i in range(4):
    forward(100)
    right(90)
What it draws

every other

i % 2 == 0 is true on every second pass.

for i in range(8):
    if i % 2 == 0:
        pass
    else:
        pass
Example
for i in range(8):
    if i % 2 == 0:
        pencolor("red")
    else:
        pencolor("blue")
    pensize(6)
    forward(30)
    right(45)
What it draws
Red and blue sides, taking turns

read a CSV with pandas

Reads the whole file into a table (a DataFrame). Numbers stay numbers.

import pandas as pd

songs = pd.read_csv("music.csv")

an app with Gradio

Gradio calls your function with what was chosen, and shows what it returns.

import gradio as gr

def answer(choice):
    return "You chose " + choice

gr.Interface(fn=answer, inputs=gr.Dropdown(["pop", "rock"]), outputs="text").launch()

for loop

Repeat the indented lines this many times.

for i in range(4):
    pass
Example
for i in range(5):
    forward(15)
    penup()
    forward(10)
    pendown()
What it draws
range(5): five dashes

counter step

Use the counter i to make each pass different.

for i in range(20):
    forward(i * 5)
    right(90)
Example
for i in range(30):
    forward(i * 5)
    right(90)
What it draws
A square spiral: each line longer than the last

load with json

Reads JSON text back into the dictionary or list that was saved.

import json

with open("game.json") as f:
    game = json.load(f)

filter a table

Keeps the rows where the test is true, as a smaller table.

rows = songs[songs["genre"] == genre]

ask an API

Asks an API at that address (params become the ?query string) and turns the JSON reply into dictionaries and lists. Plan for no connection.

import requests

try:
    reply = requests.get("https://api.open-meteo.com/v1/forecast", params={"latitude": -35.28, "longitude": 149.13, "daily": "temperature_2m_max"}, timeout=10).json()
except requests.RequestException:
    print("No connection")