Lesson 2 · Unit 06
Files and modules
Borrow ready-made code, and keep data after the program ends
What you practise
with open, reading and writing lines, JSON in and out,importand the standard library (math,random,datetime,pathlib),if __name__ == "__main__"
Try a question from this lesson
Pick one
Python keeps extra tools in modules. import math loads one: math.sqrt is its square root, math.floor rounds down. What does this program show?
import math
print(math.sqrt(49) + math.floor(2.9))Hint
The square root comes back as a number with a point. Rounding down drops everything after the point.
Correct answer
9.0
Why
The square root of 49 is 7.0, a float. floor rounds 2.9 down to 2, not up to 3. A float plus a whole number is a float: 9.0. You did not have to write either function: the module had them ready.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Modules and import
A module is a file of ready-made code. Python ships with hundreds of them: the standard library.
import math loads the module, and you reach inside it with a dot. from random import choice takes one name out, so you can use it without the dot.
import math
from random import choice
print(math.pi) # 3.141592653589793
print(math.ceil(2.1)) # 3: rounds up
coin = choice(["heads", "tails"])
print(coin) # one of the twoConcept
open, with and modes
open needs a file name and a mode. "w" writes, and wipes whatever was in the file. "a" adds to the end. No mode means read.
with gives the open file a name, here f, and closes the file when the indented block ends, even if an error happens inside it.
with open("notes.txt", "w") as f:
f.write("milk\n")
with open("notes.txt", "a") as f:
f.write("eggs\n")
with open("notes.txt") as f:
print(f.read())
# milk
# eggsConcept
JSON
A file holds text. JSON is a way of writing lists and dictionaries as text, so they can be saved and read back.
json.dumps turns data into a JSON string, and json.loads turns it back. With an open file, use json.dump(data, f) and json.load(f).
import json
stock = {"tea": 4, "milk": 0}
text = json.dumps(stock)
print(text) # {"tea": 4, "milk": 0}
back = json.loads(text)
print(back["tea"] + 1) # 59 more exercises in the app
- 3× multiple choice
- 3× type the answer
- 2× fill the blanks
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.