running total
Start the total at 0 once, then add to it on every pass.
total = 0
while total < 10:
total += int(input("Add: "))Data detective · In any playground, open Reference to copy these.
Start the total at 0 once, then add to it on every pass.
total = 0
while total < 10:
total += int(input("Add: "))Give a value a name, so you can reuse and change it.
size = 50length = 120
forward(length)
left(90)
forward(length / 2)
Work through a list, one item at a time.
for c in colours:
passpensize(6)
for c in ["red", "blue", "green"]:
pencolor(c)
forward(40)
Show text or a value in the output box.
print("Hello")Values stored under names (keys). One dictionary can hold everything about one thing.
star = {"speed": 5, "points": 1}True if the item is in the list (or the key is in the dictionary, or the letters are in the text).
if item in bag:
passEach row of the file becomes a dictionary, keyed by the column names in the first line. Every value is text.
import csv
with open("music.csv") as f:
rows = list(csv.DictReader(f))Do one thing or the other, depending on a condition.
if x > 0:
pass
else:
passfor x in [-90, -30, 30, 90]:
penup()
goto(x, 0)
if x > 0:
dot(30, "red")
else:
dot(30, "blue")
hideturtle()
Change a value every pass: read the old one, store a new one.
size = 5
for i in range(20):
forward(size)
right(90)
size = size + 5size = 5
for i in range(30):
forward(size)
right(90)
size = size + 5
Join pieces of text into one with +. Spaces only appear where they are inside the quotes.
"Hello, " + nameThe value stored under that key. The key goes in quotes. Assign to it to change it: star["speed"] = 8.
star["speed"]Opens the file to read and gives you all of it as one piece of text.
with open("save.txt") as f:
text = f.read()Keep many values in order under one name. The first item is place 0.
colours = ["red", "blue", "green"]Turn a number into text, so it can be joined: "Score: " + str(score).
str(score)strip() removes spaces at the ends; lower() and upper() change the capitals. Each gives back new text.
command = command.strip().lower()Run lines that might fail. If the named error happens, the except lines run instead of the program stopping.
try:
n = int(text)
except ValueError:
print("That is not a number.")"#" * 5 is #####. ljust pads the label to the same width, so the bars line up.
print(label.ljust(12) + "#" * n)Name a group of steps, then run it by calling its name.
def shape():
pass
shape()def zigzag():
left(45)
forward(30)
right(90)
forward(30)
left(45)
zigzag()
zigzag()
zigzag()
One count for each different value: add 1 if the key is there already, or start it at 1.
counts = {}
for row in rows:
key = row["genre"]
if key in counts:
counts[key] = counts[key] + 1
else:
counts[key] = 1A test case: nothing happens if it is true; the program stops with AssertionError if it is not.
assert clean_hours("5") == 5Draw a square by repeating forward and right four times.
for i in range(4):
forward(100)
right(90)
i % 2 == 0 is true on every second pass.
for i in range(8):
if i % 2 == 0:
pass
else:
passfor i in range(8):
if i % 2 == 0:
pencolor("red")
else:
pencolor("blue")
pensize(6)
forward(30)
right(45)
Reads the whole file into a table (a DataFrame). Numbers stay numbers.
import pandas as pd
songs = pd.read_csv("music.csv")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()Repeat the indented lines this many times.
for i in range(4):
passfor i in range(5):
forward(15)
penup()
forward(10)
pendown()
Use the counter i to make each pass different.
for i in range(20):
forward(i * 5)
right(90)for i in range(30):
forward(i * 5)
right(90)
Reads JSON text back into the dictionary or list that was saved.
import json
with open("game.json") as f:
game = json.load(f)Keeps the rows where the test is true, as a smaller table.
rows = songs[songs["genre"] == genre]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")