Objectives: LO-1.1, LO-1.2, LO-1.3
Prerequisites: none; set up your computer first, with setting up your
computer
Time: about 7 hours: 1.5 for the setup, 2 for this reading, 2 for Lab 1, and
1.5 for the practice
In this module you write your first programs and run them. You run Python three ways, print text and the results of calculations, explain your code with comments, and read the error messages that Python shows when something goes wrong. Every programmer sees error messages every day, so learning to read them is the first skill this course teaches.
Read with your computer beside you. Each section ends with something to try; type it yourself, because typing code, making mistakes, and fixing them is how programming is learned.
What a program is¶
A program is a list of instructions written in a programming language, a language with exact rules that a computer can carry out. Python is a programming language, and “Python” is also the name of the program that runs Python code: the Python interpreter. The interpreter reads your instructions one at a time, from the top down, and carries out each one before it moves on to the next.
Here is a program of three lines:
print("Hello!")
print(2 + 3)
print("Goodbye!")When Python runs it, it prints:
Hello!
5
Goodbye!print is a function, a named piece of code that does one job. Its job is to show whatever
you put between its parentheses. The first line shows the text Hello!. The second line works out
2 + 3 first, then shows the result, 5. The third shows Goodbye!.
Two things about this program matter for everything that follows:
Python does exactly what the code says. It doesn’t guess what you meant. If you misspell
print, Python stops with an error instead of working out the word you intended.Order matters. Python runs the lines in order, so the output comes out in the same order as the lines that produce it.
Three ways to run Python¶
You can give Python code in three ways. Each suits a different job, and this course uses all three.
A notebook cell¶
A notebook is a document made of cells. Some cells hold text, like this page; others hold code. When you run a code cell, by clicking in it and pressing Shift+Enter, Python runs the code, and the output appears right under the cell. The course’s labs are notebooks that you run in JupyterLab, as you did in the setup.
A notebook cell does one thing that a program file doesn’t: if the cell’s last line is a
calculation, the notebook shows its value even without print. A cell holding
3 * 2.50 + 2 * 1.25shows 10.0 under it. Only the last line gets this treatment, so a cell holding 7 / 2 on one
line and 6 / 2 on the next shows only 3.0.
The number in brackets beside a cell, such as [3], counts the cells you have run. It records the
order in which you ran them, which matters from Module 2 on.
The interactive interpreter¶
The interactive interpreter is Python waiting for you to type one line at a time. Start it in
the terminal in VS Code (Terminal > New Terminal), in your py101 folder, by typing the
path to your environment’s Python. A path says where a file is: the folders to go through,
separated by \ on Windows or / on macOS and Linux, and then the file’s name.
Windows:
.venv\Scripts\pythonmacOS and Linux:
.venv/bin/pythonPython prints a line with its version, and then its prompt, >>>, which means it is ready for
you to type. Type a line and press Enter, and Python runs it and shows the result:
>>> 2 + 3
5
>>> print("Hello!")
Hello!
>>> exit()Like a notebook cell, the interpreter shows the value of a calculation without print. Typing
exit() leaves it, and the terminal’s usual prompt comes back. The interpreter keeps nothing:
when you leave, what you typed is gone. That makes it the quickest way to check one small thing,
such as what 7 / 2 gives.
A script file¶
A script is a program saved in a file whose name ends in .py. Scripts are how real programs
are kept: you can run a script again tomorrow, change it, and give it to someone else.
To write one in VS Code:
Choose File > New File, and save it in your
py101folder ashello.py. The.pyending tells both VS Code and Python that the file holds Python code.Type the three-line program from the start of this page, and save the file.
Click the Run Python File button, a triangle in the top-right corner of the editor. VS Code opens the terminal panel, runs the script, and shows its output there.
You can also run a script by typing a command in the terminal: the path to Python, then the name of the file.
Windows:
.venv\Scripts\python hello.pymacOS and Linux:
.venv/bin/python hello.pyA script shows only what it prints. A line such as 2 + 3 on its own in a script works out the
answer and then throws it away, so this script prints 5 once, not twice:
2 + 3
print(2 + 3)If VS Code asks you to select a Python interpreter, choose the one whose path contains .venv.
VS Code’s Command Palette (Ctrl+Shift+P, or Cmd+Shift+P on macOS) has a command for it,
Python: Select Interpreter.
Choosing among them¶
| Way | Shows a calculation’s value without print | Keeps your code | Best for |
|---|---|---|---|
| Interactive interpreter | Yes | No | One quick question, such as “what is 7 / 2?” |
| Notebook cell | The last line of the cell only | Yes, with notes and output beside it | Learning and experimenting step by step |
| Script file | No | Yes | A program to run again, change, or share |
Try it. Work out 17 * 23 three ways: in the interpreter, in a cell of a new notebook
(File > New > Notebook in JupyterLab), and in a script. Which of the three needed
print to show the answer?
Printing text and numbers¶
Text in a program goes between quotation marks. A piece of text is called a string, short for
“a string of characters”. Python accepts double quotes ("Hello") or single quotes ('Hello'),
as long as both ends match. Numbers go without quotes.
print("Hello")
print(42)
print(3.5)Hello
42
3.5Give print several things separated by commas, and it prints them on one line with a space
between each. print() with nothing inside prints an empty line.
print("Total:", 10)
print()
print("Done")Total: 10
DoneTo print an apostrophe, put the text in double quotes: print("It's raining"). In single quotes,
the apostrophe would end the string early.
Worked example: a receipt¶
A shop sells notebooks at 2.50 each and pens at 1.25 each. This script prints a receipt for 3 notebooks and 2 pens, and lets Python do the arithmetic:
print("Receipt")
print("3 notebooks at 2.50:", 3 * 2.50)
print("2 pens at 1.25:", 2 * 1.25)
print()
print("Total:", 3 * 2.50 + 2 * 1.25)Receipt
3 notebooks at 2.50: 7.5
2 pens at 1.25: 2.5
Total: 10.0Look at the second line of the script. The part in quotes, "3 notebooks at 2.50:", is a string,
and Python prints it exactly as written, even though it contains numbers. The part without quotes,
3 * 2.50, is a calculation, and Python prints its result. Python writes 7.5 rather than 7.50,
because it writes a number with as few digits as it needs; Module 2 shows how to print exactly two
decimal places.
Try it. Change the receipt to 4 notebooks and 5 pens. Change both the strings and the calculations, and check the new total by hand: it should be 16.25.
Arithmetic¶
Python’s four basic arithmetic operators are + (add), - (subtract), * (multiply), and
/ (divide). Dividing with / always gives a number with a decimal point, even when the division
comes out even:
print(7 / 2)
print(6 / 2)3.5
3.0Module 2 explains why, and adds three more operators.
When a calculation has several operators, Python follows the same order as school arithmetic: multiplication and division come before addition and subtraction, and operators of the same kind run from left to right. Parentheses go first, so use them to choose the order yourself.
print(2 + 3 * 4)
print((2 + 3) * 4)
print(10 - 2 - 3)14
20
5Worked example: an average¶
Three temperature readings were 18, 21, and 24 degrees. Their average is their sum divided by how many there are. A first try leaves out the parentheses:
print(18 + 21 + 24 / 3)47.047.0 can’t be right: an average must lie between the smallest and the largest reading. Python
divided first, as the rules say: it worked out 24 / 3, which is 8.0, then 18 + 21 + 8.0.
Parentheses make it add first:
print((18 + 21 + 24) / 3)21.0Checking that an answer is reasonable, as “an average lies between the smallest and the largest value” does here, catches many mistakes that produce no error message at all.
The spaces around operators don’t change what Python does: 2+3*4 gives 14 too. This course
puts a space on each side of an operator, as most Python code does, because the code is easier
to read.
Try it. Write the calculation for the average of 4, 7, and 10 (from the course’s self-check),
and print it. It should print 7.0.
Comments¶
A comment is a note for people who read the code. It starts with #, and Python ignores
everything from the # to the end of the line.
# receipt.py: prints a receipt for one shopping trip.
print("Receipt")
print("3 notebooks at 2.50:", 3 * 2.50) # 2.50 is the price of one notebookGood comments say what a program is for, or why a line is the way it is: things the code itself
can’t say. A comment that repeats the code, such as # multiply 3 by 2.50, adds nothing.
Putting # at the start of a line of code turns the whole line into a comment, so Python skips
it. Programmers call this “commenting out” a line, and use it to switch a line off for a moment
without deleting it.
Reading error messages¶
When Python can’t carry out an instruction, it stops and prints an error message that says what went wrong and where. An error never harms your computer or your files: Python stops, you fix the code, and you run it again.
The parts of an error message¶
Suppose receipt.py has a typing mistake on its third line:
print("Receipt")
print("3 notebooks at 2.50:", 3 * 2.50)
prnt("2 pens at 1.25:", 2 * 1.25)
print("Total:", 3 * 2.50 + 2 * 1.25)Running it prints:
Receipt
3 notebooks at 2.50: 7.5
Traceback (most recent call last):
File "/home/you/py101/receipt.py", line 3, in <module>
prnt("2 pens at 1.25:", 2 * 1.25)
^^^^
NameError: name 'prnt' is not defined. Did you mean: 'print'?Read an error message from the bottom up:
The last line names the kind of error, here
NameError, and says what is wrong: Python doesn’t know any nameprnt. Here it even suggests the name you probably meant.The lines above it say where: the file, and the line number,
line 3. (The path is where the file is on your computer, so it looks different on yours. You can ignorein <module>for now; it means the line isn’t inside a function of your own, which Module 5 introduces.) Python also shows the line itself, with^marks under the part that failed.The first line,
Traceback (most recent call last):, says that the lines after it trace the steps that led to the error. From Module 5 on, these steps can be several lines deep.
Notice the first two lines of output. Python ran lines 1 and 2 and printed their output before it reached the mistake on line 3, and it never ran line 4.
In a notebook the same mistake looks a little different. The notebook names the cell instead of the file, marks the failing line with an arrow, and leaves out the suggestion:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[1], line 1
----> 1 prnt("Hi")
NameError: name 'prnt' is not definedThree kinds of error¶
A syntax error means Python couldn’t read the code at all, because it breaks the rules of how Python is written: a missing quotation mark, or a parenthesis that is opened but never closed.
print("Hello) File "/home/you/py101/hello.py", line 1
print("Hello)
^
SyntaxError: unterminated string literal (detected at line 1)A string literal is a string typed into the code, and “unterminated” means its closing quote is missing. Python reads the whole file before it runs any of it, so a syntax error anywhere stops the whole script: not one line runs, not even the lines before the mistake.
A name error means Python met a name it doesn’t know. The usual causes are a misspelling
(prnt), a capital letter in the wrong place (Print; Python treats capital and small letters as
different), and text that should have been in quotes. Without quotes, print(Hello) makes Python
look for something named Hello.
A type error means an operation was given the wrong kind of value. + can add two numbers,
and it can join two strings, but it can’t do either with a string and a number:
print("Total: " + 10)Traceback (most recent call last):
File "/home/you/py101/total.py", line 1, in <module>
print("Total: " + 10)
~~~~~~~~~~^~~~
TypeError: can only concatenate str (not "int") to strTo concatenate is to join strings end to end. str is Python’s name for a string, and int,
for a whole number. The ^ under the + points to the operation that failed. Here, giving print
two things, print("Total:", 10), does what was meant. Module 2 shows other ways.
The messages shown here are the same in Python 3.12 and Python 3.15. Newer versions of Python sometimes word a message differently, but the kind of error on the last line stays the same.
A method for fixing errors¶
Read the last line: what kind of error is it, and what does it say?
Go to the line it names, and look at the part the marks point to.
Fix one thing.
Run the code again, and read the new output. If there is a new error, start again at step 1.
For a syntax error, the line Python names is where it noticed the problem. The mistake is usually on that line, and sometimes on the line just before it.
Try it. Make each kind of error on purpose in your hello.py: delete a closing quote, then
misspell print, then add a string to a number. Run the script each time, and find the kind of
error and the line number in the message before you fix it.
Common misconceptions¶
Each row is a belief that newcomers often hold, with an example that breaks it.
| Belief | What Python does | Example that breaks it |
|---|---|---|
| Python works out what I meant | It does exactly what the code says | print("2 + 3") prints 2 + 3, because the quotes make it text |
| Capital letters don’t matter | Names are case-sensitive | Print("Hi") stops with NameError: name 'Print' is not defined |
| A line with a calculation shows its result | In a script, only print shows anything | A script whose only line is 2 + 3 prints nothing |
| Python calculates from left to right | * and / come before + and - | 18 + 21 + 24 / 3 is 47.0, not 21.0 |
| An error means I broke something | Python stops and changes nothing | Fix the line and run it again; nothing else needs repairing |
| If a script has an error, nothing in it ran | A syntax error stops everything; other errors stop at their line | The receipt with prnt on line 3 printed two lines first |
Summary¶
A program is a list of instructions. Python runs them one at a time, from the top, and does exactly what each one says.
You can run Python in a notebook cell, in the interactive interpreter, or as a script file. The interpreter and notebook cells show a calculation’s value without
print; a script shows only what it prints. Scripts are how programs are kept and shared.printshows its arguments, separated by spaces. Text goes in quotes; numbers don’t.Python’s arithmetic follows school rules:
*and/before+and-, and parentheses first./always gives a number with a decimal point.Comments start with
#, and say what code is for or why it is written that way.An error message names the kind of error on its last line, and the file and line above it. A syntax error stops a script before any of it runs; a name error or a type error stops it at the failing line.
Self-check¶
Answer each question before you open its answer.
You want to know whether Python’s
/rounds7 / 2down. Which of the three ways of running Python is the quickest way to find out, and why?Answer
The interactive interpreter: type
7 / 2at the>>>prompt and read the answer,3.5. You don’t need to keep the code, and the interpreter shows the value withoutprint.A script holds two lines,
10 * 3andprint(10 - 3). What does it print? What would a notebook cell holding the same two lines show?Answer
The script prints
7only; the value of10 * 3is worked out and thrown away. The notebook cell also shows7only: theprintshows7, and the cell’s last line is aprint, not a bare calculation, so there is no value to show.What does
print("Sum:", 2 + 3 * 2)print?Answer
Sum: 8. Multiplication comes first, so3 * 2is6, and2 + 6is8.printputs a space between the string and the number.A script prints
NameError: name 'totl' is not definedand names line 6. What is the most likely cause, and did lines 1 to 5 run?Answer
Line 6 uses the name
totl, most likely a misspelling of another name. Lines 1 to 5 ran: a name error stops the script at the line where it happens.A script prints only an error message ending in
SyntaxError: '(' was never closed, naming line 4, and none of the output from lines 1 to 3. Why didn’t lines 1 to 3 print anything?Answer
Python reads the whole file before it runs any of it. A syntax error means it couldn’t read the file, so it ran no line at all. The fix is a closing parenthesis on line 4.
Further reading¶
The Python Tutorial, chapter 2, Using the Python Interpreter, and section 3.1.1, Numbers. Python’s official introduction is written for people who have programmed before, so it moves quickly, but it is exact, and you can come back to it as you learn.
Allen B. Downey, Think Python, 3rd edition, chapter 1, Programming as a way of thinking. The course’s companion textbook, free online as notebooks. This chapter covers the same arithmetic and strings as this module, with a section on debugging.
Al Sweigart, Automate the Boring Stuff with Python, 3rd edition, chapter 1, Python Basics. A second explanation for beginners, free online, with more examples of the interpreter and of error messages.
Visual Studio Code, Getting Started with Python in VS Code. VS Code’s own guide to writing and running a script, with pictures of each step.