Lesson 1
When things go wrong
Read error messages, and catch errors with try and except.
Reading an error
When Python can’t carry on, it stops and tells you three things: the type of error, a message, and the line. Read it from the end: the last line is the most useful.
NameError: a name that doesn’t exist (often a typo)
TypeError: the wrong kinds of value together, like"5" + 5
ValueError: the right type but a bad value, likeint("abc")
IndexErrorandKeyError: no such position in a list, or key in a dictionary
ZeroDivisionError: dividing by zero
Run the example: the third line never happens.
print("Start")
print(10 / 0)
print("This line never runs")
try and except
Put code that might fail inside try:. If an error happens, Python jumps to the matching except block instead of stopping, and the program carries on.
Name the error you expect, like except ValueError:, so other mistakes still show up.
text = "twelve"
try:
n = int(text)
print(n * 2)
except ValueError:
print(f"Sorry, {text} is not a number.")
print("Still running!")
Raising your own errors
raise ValueError("message") causes an error on purpose. Functions do this when they’re given something that makes no sense.
except ValueError as error: catches it and gives you the message.
def set_age(age):
if age < 0:
raise ValueError("an age cannot be negative")
return age
try:
set_age(-5)
except ValueError as error:
print(f"Problem: {error}")
Lesson 2
Files
Save text to a file, add to it, and read it back.
Writing a file
open("diary.txt", "w") opens a file for writing. It makes the file, or empties it if it’s already there.
with ... as f: closes the file for you when the indented block ends. f.write() doesn’t start a new line by itself, so end each line with "\n".
(Your files here go in a pretend folder that’s emptied each time you run your code.)
with open("diary.txt", "w") as f:
f.write("Day 1: I learned Python.\n")
f.write("Day 2: Files!\n")
print("Saved.")
Adding and reading
"a"opens a file to add to the end, keeping what’s there
open("list.txt")on its own opens it to read
f.read()gives the whole file as one string;for line in f:goes through it a line at a time, and.strip()removes the"\n"at the end of each
with open("list.txt", "w") as f:
f.write("eggs\nmilk\n")
with open("list.txt", "a") as f:
f.write("bread\n")
with open("list.txt") as f:
for line in f:
print(line.strip())
Lesson 3
Classes and objects
Make your own types of thing, with their own data and abilities.
A class is a blueprint
A class describes a new type of thing. You can then make as many objects from it as you like, each with its own data.
__init__ (two underscores on each side) runs when you make an object. self is the object being made, and self.name = name stores the name on it.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rex = Dog("Rex", 3)
luna = Dog("Luna", 5)
print(rex.name)
print(luna.age)
Methods: things objects can do
A method is a function inside a class. Its first parameter is always self, so it can read and change the object’s data.
Call it with a dot: clicks.add(). Python passes the object in as self for you.
class Counter:
def __init__(self):
self.count = 0
def add(self):
self.count += 1
clicks = Counter()
clicks.add()
clicks.add()
print(clicks.count)
Recap
What Level 6 covers, in a few lines.
- When something goes wrong, Python stops and says what kind of error it was, why, and on which line.
NameError,TypeError,ValueError,IndexError,KeyErrorandZeroDivisionErrorare the common ones. try:runs risky code, andexcept ValueError:says what to do if that error happens, so the program keeps going.raisecauses an error on purpose.with open("file.txt", "w") as f:opens a file to write ("w"replaces it,"a"adds to the end);open("file.txt")reads it.f.write()doesn’t add a new line: add"\n"yourself.- A class is a blueprint for your own type of thing.
__init__runs when you make one, and stores its data onself. - Methods are functions inside a class, with
selfas the first parameter. Each object keeps its own data.
Now try it in Python School
Write real Python and run it right there, with a check after every step and a test at the end of each level. Free.