print() is fine for quick experiments. In a real program you want more control: messages carry a level, and one setting decides how much detail reaches the screen.The
logging module gives every message a severity tag:- DEBUG – development noise
- INFO – normal milestones (user logged in, order placed)
- WARNING – something unexpected but handled
- ERROR – an operation failed
- CRITICAL – the program cannot continue
logging.basicConfig() sets up the main logger, called root, which every other logger passes its messages up to. Three of its arguments:level=logging.INFO – messages less serious than INFO (here, DEBUG) are skipped.format= – the pattern for each line, in the old % style from Formatting output: %(levelname)s puts in the level, %(name)s the logger's name, and %(message)s your message.stream=sys.stdout – send each line to the output, where print() writes, so this course can read it. sys is a module about Python itself, and sys.stdout is that output.import logging
import sys
logging.basicConfig(
level=logging.INFO,
format='%(levelname)s:%(name)s:%(message)s',
stream=sys.stdout,
force=True,
)
logger = logging.getLogger('shop')
# hidden: DEBUG is less serious than INFO
logger.debug('building cart for user 42')
logger.info('order placed: item=book qty=1')Notice the output is one line:
The DEBUG line never appears. If you later set
Each level has a method named after it:
INFO:shop:order placed: item=book qty=1The DEBUG line never appears. If you later set
level=logging.DEBUG, that same logger.debug(...) call prints, and the call itself never changes.Each level has a method named after it:
logger.debug(), logger.info(), logger.warning(), logger.error() and logger.critical().Quick statistics with statistics
import statistics
data = [2.5, 3.0, 4.5, 6.0]
print(statistics.mean(data)) # average
# the middle value, or halfway between
# the two middle values
print(statistics.median(data))
print(statistics.mode([1, 1, 2])) # most common
# with no repeats, mode gives the first one
print(statistics.mode([9, 7, 8])) # 9
print(round(statistics.stdev([2, 4, 6]), 3))Measuring how long code takes
import time
t0 = time.perf_counter()
for i in range(1_000):
pass
elapsed = time.perf_counter() - t0
print(f'{elapsed:.6f} seconds')In the loop above,
1_000 is just 1000: the _ only makes long numbers easier to read.timeit.timeit runs a function many times and returns the total time in seconds. It is handy for comparing two ways of doing the same job, without writing your own loop.import timeit
def square(n):
return n * n
total = timeit.timeit(lambda: square(12), number=1000)
print(f'{total:.6f} seconds for 1000 calls')