Space Python Loading Python…

Logging instead of print

Fix the codeMedium 2 stages

While chasing a fuel sensor bug, someone added a print() for every tank. The bug is fixed, but the prints stayed, and the pre-burn check now buries its one important line, an empty tank, under lines nobody needs.

Switch to the logging module, where every message has a level and you decide which levels to show.

Replace each print() with the logging call for its level: logging.debug(), logging.info(), logging.warning() or logging.error(), and drop the level from the text, since the format adds it. With the level set to INFO, the debug lines disappear:

INFO TANK-1 ok: 78.3%
WARNING TANK-2 is low: 12.4%
ERROR TANK-3 is empty
INFO Tank check complete

Leave the basicConfig() line as it is. The hidden tests switch it to DEBUG and expect your debug lines to come back.

Only what matters
No prints left

Finish stage 1 to unlock this stage.

In a bigger program, every module logs. Give this code its own logger, log = logging.getLogger("fuel"), log through it, and add its name to the format with %(name)s. Switch on debug records for this logger only with log.setLevel(logging.DEBUG):

DEBUG fuel: checking TANK-1: 78.3%
INFO fuel: TANK-1 ok: 78.3%
DEBUG fuel: checking TANK-2: 12.4%
WARNING fuel: TANK-2 is low: 12.4%
DEBUG fuel: checking TANK-3: 0.0%
ERROR fuel: TANK-3 is empty
INFO fuel: Tank check complete

The rest of the program stays at INFO: only the fuel logger shows its debug lines.

Named, with debug on
Through the fuel logger
You're not logged in, so your progress is kept in this browser only. Log in to save it, and to use hints and solutions.

Hints

Import System Modules

import-system-modules.py
# A module is a toolbox someone else already built and tested for you

# Plain import brings in the whole module
import sys
import platform
import math

# from ... import brings in just one tool
from math import sqrt

# as gives a module a shorter nickname
import random as rng

# With a plain import: module name, a dot, then the tool
print("Python version:", platform.python_version())
print("Running on:", platform.system())
print("Python lives at:", sys.executable)

# math carries constants you would not want to type from memory
radius_km = 6371
print("Earth circumference:", round(2 * math.pi * radius_km), "km")

# sqrt arrived on its own, so it needs no dot in front
print("Square root of 9:", sqrt(9))

# rng is simply a nickname for random
print("Random sol of the Martian year:", rng.randint(1, 687))
Open the full example
script.py
PythonLn 1, Col 1Spaces: 4
Loading the Python environment…

Separate arguments with commas. They're passed on every Run as sys.argv[1:].