← Teacher guide Markdown for Prepare

Working with text: cheat sheet

Deeper Python in the console · In any playground, open Reference to copy these.

ask and reply

Ask a question, store the typed answer, and use it in a reply.

name = input("What is your name? ")
print("Hello, " + name)
What it draws
Asks for a name, then says hello

if / else

Do one thing or the other, depending on a condition.

if x > 0:
    pass
else:
    pass
Example
for x in [-90, -30, 30, 90]:
    penup()
    goto(x, 0)
    if x > 0:
        dot(30, "red")
    else:
        dot(30, "blue")
hideturtle()
What it draws
Red when x > 0, else blue

grow value

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 + 5
Example
size = 5
for i in range(30):
    forward(size)
    right(90)
    size = size + 5
What it draws
The same spiral, grown by an update

strip and lower

strip() removes spaces at the ends; lower() and upper() change the capitals. Each gives back new text.

command = command.strip().lower()

check then convert

Check typed text with isdigit before turning it into a number.

text = input("How many? ")
if text.isdigit():
    number = int(text)
    pass
else:
    print("Please type a number.")
Example
text = input("How many tickets? ")
if text.isdigit():
    print("That will be $" + str(int(text) * 12) + ".")
else:
    print("Please type a number.")
What it draws
A checked ticket total

variable

Give a value a name, so you can reuse and change it.

size = 50
Example
length = 120
forward(length)
left(90)
forward(length / 2)
What it draws
length = 120, then half of it

print

Show text or a value in the output box.

print("Hello")

input

Show a question in the console, wait for an answer, and store what was typed. It is always text.

name = input("What is your name? ")

join text

Join pieces of text into one with +. Spaces only appear where they are inside the quotes.

"Hello, " + name

split

Cut text into a list of words at the spaces: "go north".split() is ["go", "north"].

words = command.split()