Space Python Loading Python…

Magic numbers

Fix the codeEasy 3 stages

The structural report for Python One's lander works out the weight of each part. The code is correct, but it's full of bare numbers like 9.81 and 1000. Programmers call them magic numbers: they work, but nobody reading the code knows what they mean, and changing one means finding every copy.

Predict what the report prints, find out where the magic numbers hide, then give them names. Refactoring means improving code without changing what it does, so the output has to stay exactly the same.

Don't run the code yet. Read it and decide what it will print on its first line. Write your guess in prediction, at the top, between the quotes. Then run it and compare.

Any guess passes this stage: the point is to think before you run. After you check, you'll see your prediction next to what Python printed.

Work out the lander's line: its mass times 9.81, divided by 1000, with two decimal places.

Predict, then run
Leave the program as it is

Finish stage 1 to unlock this stage.

Investigate. Count how many times 9.81 appears in the two prints and store the number in times_981. Every copy is a place someone would have to change if the report were rerun for the Moon.

Modify. Add two constants above the prints, written in capitals so everyone knows they don't change, for example GRAVITY = 9.81 and N_PER_KN = 1000. Use them in both prints instead of the bare numbers. The output must stay exactly the same:

Lander: 11.77 kN
Rover: 3.43 kN
Count the copies of 9.81
Name the numbers, keep the output

Finish stage 2 to unlock this stage.

The rover's test drive happens on Mars, where gravity is 3.71 m/s². Write the weight report with constants from the start: one for Mars's gravity and one for newtons per kilonewton, both in capitals. Print:

Rover on Mars: 3.80 kN
Print the weight on Mars
Use named constants
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

Creating Variables

creating-variables-python.py
# Variables store data under a name
# Create them by assigning a value with =

ship_name = "Project Hail Mary"
crew_count = 3
fuel_remaining = 78.4
in_deep_space = True

print("Ship:", ship_name)
print("Crew:", crew_count, "people")
print("Fuel remaining:", fuel_remaining, "%")
print("In deep space:", in_deep_space)
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:].