Your first program

Topic 4 of 4 in Getting started6 min readBeginnerFree course

Overview

In this lesson you’ll write a full program, learn the handful of rules every Python line follows, and — most importantly — learn to read error messages. Every programmer, at every level, sees errors all day. The difference between a beginner and an expert is mostly how quickly they can read one and fix it.

print()

print() is a function that displays values:

Python
print("Hello, world!")
print(42)
print("The answer is", 42)
print()                         # an empty line
print("a", "b", "c", sep="-")   # a-b-c
print("Loading", end="...")     # no new line at the end
print("done")                   # Loading...done
  • Text goes in quotes: "Hello" or 'Hello' — both work, just be consistent.
  • Separate several values with commas; print puts a space between them (change it with sep=).
  • Each print ends with a new line (change it with end=).

The rules of a Python line

One statement per line. Python runs lines from top to bottom:

Python
print("first")
print("second")

Case matters. print, Print and PRINT are three different names; only print exists.

Indentation means something. In many languages, spaces at the start of a line are just style. In Python, indentation shows which lines belong together (you’ll use it from If statements on). For now: don’t indent lines unless you mean to. An unexpected indent is an error:

Python
print("one")
    print("two")    # IndentationError: unexpected indent

Brackets and quotes must be closed. Every ( needs a ), every " a matching ".

Reading error messages

When Python can’t run your program, it prints a traceback:

Reading an error message (traceback). Traceback (most recent call last): File “/home/asha/hello.py”, line 3, in <module> shows where — the file and line; the next line is the code itself, print(“Total: “ + total); carets under it point at which part failed; and the last line, TypeError: can only concatenate str (not “int”) to str, gives the error type and message. Read it from the bottom up: 1, the last line says what kind of error and why; 2, the lines above say where — go to that file and line; 3, fix, save and run again.

Read from the bottom up:

  1. The last line says what went wrong: the error type (TypeError) and a message.
  2. The lines above say where: the file and line number, and the line of code itself, often with ^ marks under the exact part that failed.
  3. Go to that line, fix it, run again.

The errors you’ll meet first

SyntaxError

The code isn’t valid Python, so nothing runs at all:

Python
print("Thank you for visiting!"
Text
  File "receipt.py", line 8
    print("Thank you for visiting!"
         ^
SyntaxError: '(' was never closed

Python’s messages are now very specific — “was never closed”, “invalid syntax. Perhaps you forgot a comma?”, “expected ‘:’”. Look at the line shown and the line before it: an unclosed bracket on one line often shows up as an error on the next.

NameError

You used a name Python doesn’t know — usually a typo:

Text
NameError: name 'itme' is not defined

When the typo is close enough to a real name, Python adds a suggestion — the capitalisation mistake gives NameError: name 'Print' is not defined. Did you mean: 'print'?. For bigger slips like swapped letters (itme) it can’t be sure, so compare the name carefully with where you defined it.

TypeError

You combined values of types that don’t go together, such as text and a number:

Python
print("Price: " + 4)
Text
TypeError: can only concatenate str (not "int") to str

+ joins text to text. Convert the number with str(4), or use commas in print("Price:", 4). You’ll learn proper ways to build text in Strings.

IndentationError

An unexpected indent, or a missing one after a line ending in :.

A debugging method

  1. Run often, so you know the error is in the few lines you just wrote.
  2. Read the last line of the traceback. Look up unfamiliar error types.
  3. Go to the line it names (and the one before).
  4. Fix one thing, then run again — errors often hide other errors behind them.
  5. Still stuck? Copy the last line of the error into a search engine — someone has had it before.

Mindset: an error message isn’t Python telling you off — it’s Python telling you exactly where to look. Read it, every time.

Exercise

Fix a broken receipt printer

The starter program should print a small shop receipt, but it has four bugs — a syntax error, a name error, a type error and a capitalisation mistake. Run it, read each error message, fix one bug at a time, and run again until it prints the receipt exactly as shown in the comment at the bottom.

Python
shop = "Corner Cafe"
item = "Latte"
price = 4

print("=== " + shop + " ===")
print("Item: " + itme)
Print("Price: " + price + " dollars")
print("Thank you for visiting!"

# Expected output:
# === Corner Cafe ===
# Item: Latte
# Price: 4 dollars
# Thank you for visiting!

Summary

  • print() displays values; separate several values with commas and Python adds spaces.
  • Python is case-sensitive: print works, Print is an unknown name.
  • Each statement normally goes on its own line; indentation has meaning, so don’t indent lines at random.
  • Read tracebacks from the bottom: the last line names the error type and message, the lines above give file and line number.
  • Fix one error at a time and rerun — every programmer makes mistakes; reading errors is a core skill.