← Reference

Real tools: cheat sheet

Machine learning with Gradio · 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

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()

predict with a model

The new example needs the same columns, in the same order, as the training data.

mystery = pd.DataFrame([[47.0, 215.0]], columns=X.columns)
print(model.predict(mystery)[0])

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

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")

train and score a model

fit learns from the training examples; score tests on the held-back ones (1.0 is 100%).

from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1)
model = KNeighborsClassifier(n_neighbors=1)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))