Lesson 2
Constants
Some values should never change while the program runs: the number of seconds in a minute, the maximum number of players, the speed of light.
from typing import Final
MAX_PLAYERS: Final = 4
GAME_NAME: Final = "Treasure Hunt"- Constants are written in CAPITAL_LETTERS. That tells other programmers: "do not change this".
- Python does not lock the box by itself. Adding
: Finaltells ty to warn you in Zed if you accidentally change it anyway. - Why bother? If the number 60 is used in ten places and you write
SECONDS_PER_MINUTEinstead, everyone can see what the number means.
Lesson 2 · Try it
Play with constants
Press Run, then try to:
- Change
minutesto 120. What do you get? - Add a constant
HOURS_PER_DAYand print how many minutes there are in a day. - Add
SECONDS_PER_MINUTE = 100at the bottom. Python allows it here, but Zed with ty would underline it. Try it in Zed later!
Output
Press ▶ Run to see what happens.
Lesson 2 · Exercise
Cannonballs
A pirate ship has 8 cannons, and each cannon needs 3 cannonballs. Make a constant BALLS_PER_CANNON, calculate total_balls, and print the answer.
Output
Press ▶ Run to see what happens.
💡 Need a hint?
Write BALLS_PER_CANNON: Final = 3 on the line with the ... and then total_balls = cannons * BALLS_PER_CANNON