Skip to content

Your first Python: print, comments and errors

BeginnerLesson 1 of 145 min

Run your first Python in the browser: print text and sums, leave notes for yourself in comments, and learn to read an error message calmly.

A Python program is a list of instructions in a text file. Python reads it from the top, one line at a time, and does what each line says. The editor on the right is that file: write some lines, press Run (or Ctrl+Enter, ⌘+Enter on a Mac), and the output appears below it.

Printing

print() shows whatever you put between its brackets:

print("Good morning")
print(3 + 4)
print("Tickets left:", 12)
Good morning
7
Tickets left: 12

Text goes inside quotes ("…" or '…', either works). Without quotes, Python treats what you wrote as something to work out: 3 + 4 is a sum, so it prints 7. Give print several things separated by commas and it prints them on one line with a space between.

Comments

Anything after a # on a line is a comment. Python skips it; it's a note for the people who read the code, which includes you next week.

# Work out the cost of three coffees
print(3 * 2.5)  # 2.5 each

Errors are friends

Sooner or later Python stops and prints an error instead. That's not a failure, it's Python telling you exactly what confused it. Try this:

print("one")
prnt("two")

The output ends with a traceback:

one
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    prnt("two")
    ^^^^
NameError: name 'prnt' is not defined

Read it from the bottom: the last line names the kind of error (NameError) and what went wrong. Above it is the line that failed, with ^^^^ under the part Python stumbled on, and above that its line number. Notice that one was printed first: Python ran line 1 before it got stuck on line 2.

Two errors you'll meet a lot:

ErrorUsually means
NameErrora name Python doesn't know: a typo, or text without quotes
SyntaxErrorPython couldn't read the line: a missing quote, bracket or colon

Try it:Delete the closing ) from a print line and run it. Read the SyntaxError: Python points at where it got lost.

More in the Python docs: print() and errors and exceptions.

Your turn

Make the program print two lines: Hello, Python! first, then the answer to 6 * 7, worked out by Python (no typing 42 yourself). Add a comment that says what the program does.

Next →