
Code
Enums: Named Choices
Using plain strings for fixed choices invites bugs: is it "rare",
"Rare" or "rair"? An Enum defines a closed set of named
constants, and a typo becomes an immediate error.
from enum import Enum
class Weather(Enum):
CLEAR = 1
FOG = 2
STORM = 3
today = Weather.FOG
print(today) # Weather.FOG
print(today.name) # FOG
print(today.value) # 2
print(Weather(3)) # Weather.STORM (look up by value)
print(Weather["CLEAR"]) # Weather.CLEAR (look up by name)
print(today is Weather.FOG) # True
for w in Weather: # loop over every member
print(w.name) # CLEAR, then FOG, then STORM
Members are their own objects: Weather.FOG == 2 is False. Compare
members with members, and use .value when you need the raw number.
Pip tip: if you don't care about the values,
enum.auto()numbers the members for you.
Assignment
- Finish
Raritywith membersCOMMON = 1,RARE = 2,LEGENDARY = 3. glow(rarity)returns"dim"for COMMON,"bright"for RARE and"blinding"for LEGENDARY.upgrade(rarity)returns the next rarity up. LEGENDARY stays LEGENDARY.
- Finish
Raritywith membersCOMMON = 1,RARE = 2,LEGENDARY = 3. glow(rarity)returns"dim"for COMMON,"bright"for RARE and"blinding"for LEGENDARY.upgrade(rarity)returns the next rarity up. LEGENDARY stays LEGENDARY.
main.py Python sleeping
Press Run to try your code, then Check to test it.