Typing code exactly
Brackets, quotes, indentation and the look-alike characters that stop a program.
What it covers7
Why it matters
A person reading your note forgives a missing bracket. Python doesn't: it reads characters, not intentions. In a first week of coding, most of what goes wrong is typing, not thinking: a bracket left open, a quote pasted from a document, a capital letter, a few stray spaces. Learning to see those takes about twenty minutes and saves hours. The habit carries on into AI work, where a prompt, a settings file and a model's reply are all exact text too.
What you'll be able to do
- Find and type the characters code is built from: three kinds of brackets, two quotes, the colon, the underscore and the hash
- Close every bracket and quote you open, and find the one that was left open
- Start each line where it belongs: at the left edge, or four spaces in
- Spot the look-alikes that stop a program: curly quotes, a capital letter, l for 1 and O for 0
Show the answer
print("Hello")
Only the first is exact: a lowercase print, round brackets, and a quote at each end of the text. Each of the others is one character away, and one character is enough. This lesson is about seeing those characters.
The idea: Python reads one character at a time
This lesson rests on Your first program: Python runs the text you typed, and it stops at the first character it can't read.
Step through. Python accepts a line exactly as typed or stops at the first character it can't read.
The characters code is made of
Ordinary writing uses letters, a few commas and a period. Code uses a wider set, and each character has one job. Find every one of these on your keyboard now. On a US keyboard the square brackets sit to the right of the letter P, the curly ones are the same keys with Shift, and the round ones are Shift with 9 and 0. Other layouts put them elsewhere.
| Character | Name | You've seen it |
|---|---|---|
( ) | round brackets, or parentheses | around what print shows |
[ ] | square brackets | coming up, in the Lists lesson |
{ } | curly brackets, or braces | coming up, in the Dictionaries lesson |
" " and ' ' | double and single quotes | around text |
: | colon | coming up: it ends a line that opens a block |
_ | underscore | coming up: it joins words in a name, as in total_price |
# | hash | it starts a comment |
= | equals sign | coming up, in the Variables lesson |
Two pairs are easy to mix up. The underscore _ sits low on the line; the hyphen - sits in the middle and means minus. The colon : is two dots; the semicolon ; is a dot over a comma, and you won't need it.
Run this to see them all printed. Then find any you had to hunt for, and type it a few times in the box.
print("round ( ) square [ ] curly { }") print("colon : underscore _ hyphen - hash # equals =") print('a double quote: "') print("a single quote: '")
The last two lines show a trick from the first lesson. Text wrapped in single quotes can hold a double quote, and text wrapped in double quotes can hold a single one.
print?Show the answer
print("Order sent")
Calling print takes round brackets. Square and curly brackets have other jobs, which later lessons teach, and angle brackets mean less-than and greater-than.
Print("Hi") when a person would know what you meant?Write a sentence or two, then compare it with a good answer in the lesson.
In Python: the mistakes it reports
Purpose. Learn the three kinds of typing mistake and the one-line report each one gives.
Everything you open, you close
Brackets and quotes come in pairs. An opening bracket says "something starts here", and Python keeps reading until it finds the closing one. A quote works the same way: text starts at the first quote and runs to the next quote of the same kind.
So the first habit is to count. Every ( needs a ). Every opening quote needs a closing one. Many editors, the academy's included, type the closing character for you the moment you type the opening one. Let them: it's one less thing to forget.
Brackets can sit inside brackets, like a small box inside a bigger one. The inner pair closes first:
print("Total:", (2 + 3) * 4)
Count them: two opening, two closing. The inner pair (2 + 3) is worked out first, which gives 5, and 5 times 4 is 20.
Now leave one off. This cell is broken on purpose, so run it and read the last line of the report:
print("Total:", (2 + 3) * 4
Python says '(' was never closed. It points at the bracket that was opened, not at the place where the closing one should go, because it can't know where you meant to put it. An unclosed quote gets its own message: unterminated string literal, which means "this text was started and never ended".
print((2 + 3) * (4 - 1))
Show the answer
15
Three open and three close, so it runs. The two inner pairs are worked out first: 5 and 3. Then 5 times 3 is 15.
SyntaxError: unterminated string literal. Using the habit from the first lesson, what do you do first?Show the answer
Go to the line the report names and look for a quote with no partner
The last line of a report names the problem, and the lines above it name the place. "Unterminated string" means text that was opened with a quote and never closed, so you look on that line for the quote without a partner.
Close what's open
Each of these three lines is missing one closing character. Add them so the program prints Order received, then Items: 3, then Total: 40. Change nothing else.
print("Order received" print("Items: 3) print("Total:", (12 + 8) * 2
Where a line starts
In most writing, the space at the start of a line is decoration. In Python it has a meaning. Spaces at the start of a line are called indentation, and they say which lines belong together.
So far every line you've written starts at the left edge, and that's the rule for a line that stands alone. An extra space in front of it is a mistake Python won't let pass:
print("first") print("second")
The message is IndentationError: unexpected indent: the second line is pushed in, and nothing above it asked for that.
Something does ask for it soon. A line that ends with a colon opens a block, and the lines of the block sit four spaces in. Here is the shape. You'll meet if properly in the Decisions lesson, so look only at where each line starts:
if 5 > 3: print("five is bigger") print("done")
The colon opens the block. The indented line belongs to it. The last line is back at the left edge, so it's outside the block. In the academy's editor, and in most others, the Tab key types the four spaces for you.
Spaces in the middle of a line are much freer. Python ignores them between the pieces of a line, though never inside a name: pr int is two unknown words. Inside quotes every space is kept, because it's part of the text.
print("a b") print("a", "b")
Show the answer
a b a b
The first line's three spaces are inside the quotes, so they print. On the second line the spaces after the comma are outside any quotes, so Python ignores them, and print puts its usual single space between the two values.
Straighten it out
This list should print as four lines, but two of its lines are pushed in for no reason. Fix where the lines start so the program runs. Leave the text inside the quotes as it is.
print("Packing list") print("- tent") print("- stove") print("Done")
Worked example: three typos, found one at a time
A receipt script was typed in a hurry:
print("Receipt"
Print("Tent:", 120)
print("Total:", 120 + 15)
Python stops at the first problem it meets, so the fixes come one at a time. Run 1 reports '(' was never closed on line 1: add the ). Run 2 reports unexpected indent on line 3, because Python checks the shape of the whole program before it runs any of it: delete the two spaces. Run 3 gets as far as line 2 and reports NameError: name 'Print' is not defined: make the P lowercase. Below is the script after all three fixes.
print("Receipt") print("Tent:", 120) print("Total:", 120 + 15)
Three runs, three reports, three one-character fixes. The order is worth noticing: the two mistakes Python can see by reading (the bracket and the indent) are reported before anything runs, and the unknown name only when the program reaches that line.
Write a sentence or two, then compare it with a good answer in the lesson.
In AI work: pasted and AI-written code
Purpose. Most code you run now arrives by paste, from a chat window or an AI assistant. It carries the look-alikes from here, so you read it the way you type it.
Look-alikes
Some mistakes are hard to see because the wrong character looks like the right one.
Curly quotes. Word processors, phones and chat apps turn straight quotes into curly ones: “ ” in place of ". They look tidier in a letter, and Python can't read them. Code copied from a document or a message often carries them along:
print(“Hello”)
The message names the stranger: invalid character '“' (U+201C). The code in brackets is that character's number in the list of every character computers know, so you can tell it apart from the straight one. The fix is to delete each curly quote and type a straight one in the editor. A long dash pasted in place of a minus sign fails the same way.
Capitals. print and Print are different names. So are total and Total.
Letters and digits. A lowercase l looks like the digit 1, and a capital O looks like 0. Typing l0 when you meant 10 gives a name Python has never heard of. The academy's editor uses a font that draws these differently, and so do other code editors: one reason to write code there and not in a document.
When a line looks right and Python still refuses it, read it one character at a time, saying each out loud: "print, open bracket, quote, H, i, quote, close bracket". It feels slow, and it finds what a glance misses.
invalid character '”' (U+201D). What is the most likely cause?Show the answer
The chat app turned the straight quotes into curly ones
Chat apps and word processors swap straight quotes for curly ones. Python names the character it can't read; delete each curly quote and type a straight one.
print("Total:", l0)
Show the answer
A NameError: l0 is a name Python doesn't know
A letter followed by a digit is a valid name, so this isn't a syntax problem. Python goes looking for something called l0, finds nothing, and reports a NameError when it reaches the line.
A line pasted from a chat
A line pasted from a chat message won't run. Find the characters Python can't read and fix them so it prints Order shipped.
print(“Order shipped”)
Write a sentence or two, then compare it with a good answer in the lesson.
Practice what you just read
- 7 code examples you can edit and run
- a practice exercise that checks your code
- a 5-question quiz
- 9 review cards for spaced repetition
Try a quiz question
Which of these lines does Python accept?
Before this lesson
Where this lesson leads.
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Phase 0 · about 32 hours of study
Tools
Python, the terminal and calling APIs
46 lessons All free
- Your first program FreeRun Python, print output, and read an error message without panicking.24 min
- Typing code exactly FreeBrackets, quotes, indentation and the look-alike characters that stop a program.26 min
- Variables FreeGive values names so your program can remember and reuse them.24 min
- Numbers and arithmetic FreeIntegers, decimals, rounding, and the math behind every metric.30 min
- Strings and f-strings FreeWork with text: join it, slice it, clean it, and format it.30 min
- Decisions with if/else FreeCompare values and choose what happens next.35 min
- Fractions, ratios and rates FreeShares, rates, percentage points and ratios, with Python doing the arithmetic.35 min
- Ranges and edges in code FreeAt least, under and between as symbols; intervals with each end in or out; bands with no gaps.32 min
- Lists FreeKeep many values in order, then index, slice and change them.28 min
- Files, folders and paths FreeWhat a file's name tells you, paths as directions through folders, and where a relative path starts.30 min
- Loops FreeRepeat work over every item without copy-pasting code.35 min
- Formulas: order, powers and rearranging FreeWork a calculation in the right order, fill in a formula, and turn it around to find what's missing.24 min
- Loops that add and count: sequences, sums and combinations FreeSequences that add or multiply each step, a formula for any term, and adding a sequence up.34 min
- Dictionaries FreeLook values up by name: the shape of almost all real-world data.40 min
- Functions FreePackage steps into reusable, testable pieces with inputs and outputs.35 min
- While loops FreeRepeat until something changes: goals reached, answers valid, tasks done.38 min
- Functions as values FreeStore functions, pass them in with key=, and accept any number of arguments.40 min
- Comprehensions FreeFilter and transform a whole collection in one readable line.38 min
- Errors and exceptions FreeRead tracebacks, and handle the failures you expect.38 min
- Finding bugs when nothing crashes FreeA method for wrong answers: expected against actual, reproduce, look inside, fix one thing.36 min
- Sets: unique items and fast lookups FreeDuplicates, fast membership, set operations and comparing two lists.34 min
- Modules and imports FreeUse Python's standard library instead of reinventing it.38 min
- Classes and objects FreeBundle data with the functions that work on it.38 min
- Inheritance and class attributes FreeBuild classes on other classes, and share values across every object.35 min
- Review: find the slip (Python core) FreeTen slips that run without an error, found by working a tiny input by hand, and the construct sheet for NumPy and PyTorch code.30 min
- JSON FreeThe text format APIs and LLMs use to exchange structured data.34 min
- Files and CSV data FreeRead and write files, and turn a spreadsheet export into Python data.33 min
- NumPy arrays FreeDo math on whole columns at once, the foundation of every ML library.30 min
- NumPy in practice: shapes, types and picking values FreeReshape, view and copy, where and clip, top-k, stacking and the (N, C, H, W) batch a model expects.35 min
- DataFrames with pandas FreeLoad a table, pick rows and columns, and summarize groups in a few lines.40 min
- Charts with Matplotlib FreeLine, bar, scatter, histogram and box plots, labeled and honest.42 min
- Project: images are arrays FreeGray, crop, brighten, watermark and palette tools built on NumPy and Pillow.45 min
- The terminal FreeNavigate folders and run programs by typing commands.30 min
- Version control with git FreeSave snapshots of your work, undo mistakes, and share code.30 min
- Packages and environments FreeInstall libraries with pip and keep projects isolated with venv.25 min
- Python on your own computer FreeInstall Python and VS Code, make a virtual environment, then run, debug and test a project.45 min
- How APIs work FreeRequests, responses, methods, status codes and headers.30 min
- Calling APIs from Python FreeSend requests, read JSON responses, and handle failures.35 min
- API keys and secrets FreeAuthenticate safely and keep keys out of your code.25 min
- Your first LLM call FreeSend messages to a model and read its reply, tokens and stop reason.30 min
- Capstone: ad-copy reviewer FreeCombine files, functions, JSON and an LLM call into one small tool.40 min
- Dates, times and time zones Freedatetime, timedelta, formats, time zones and the traps when clocks change.42 min
- Regular expressions FreeFind, check, extract and clean text patterns with the re module.42 min
- Sending email and text messages FreeEmailMessage, smtplib, mail merge and an SMS API, with secrets kept out of code.42 min
- Web pages: HTML and CSS FreeRead and write HTML, what forms send, CSS selectors and escaping.42 min
- Scraping web pages FreeBeautiful Soup, one record per item, pagination and robots.txt.45 min
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write