

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Sum Types
incomplete
2: Union Types
incomplete
3: Enums
incomplete
4: Sum Types
incomplete
5: Match
incomplete
6: Sum Types Practice
incomplete
This lesson's interactive features are locked, please to keep using them
Let's take another look at our example Enum from the previous lessons:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
Python has a match statement that tends to be a lot cleaner than a series of if/elif/else statements when we're working with a fixed set of possible values (like a sum type, or more specifically an enum):
def get_hex(color: Color) -> str:
match color:
case Color.RED:
return "#FF0000"
case Color.GREEN:
return "#00FF00"
case Color.BLUE:
return "#0000FF"
# default case (invalid Color)
case _:
return "#FFFFFF"
If you have two values to match, you can use a tuple:
class Shade(Enum):
LIGHT = 1
DARK = 2
def get_hex(color: Color, shade: Shade) -> str:
match (color, shade):
case (Color.RED, Shade.LIGHT):
return "#FFAAAA"
case (Color.RED, Shade.DARK):
return "#AA0000"
case (Color.GREEN, Shade.LIGHT):
return "#AAFFAA"
case (Color.GREEN, Shade.DARK):
return "#00AA00"
case (Color.BLUE, Shade.LIGHT):
return "#AAAAFF"
case (Color.BLUE, Shade.DARK):
return "#0000AA"
# default case (invalid combination)
case _:
return "#FFFFFF"
The values after match (color and shade) are compared against enum members in each case (Color.RED and Shade.LIGHT). If a match is found, the code in the block is executed.
Complete the convert_format function. Using the enum DocFormat, it should support 3 types of conversions:
h1 tag in Markdown syntax – one string representing one line. Replace the leading # with an <h1> and add a </h1> to the end.# This is a heading → <h1>This is a heading</h1>[PDF] tag to the beginning and end of the content.[PDF] tags and the content: This is some text → [PDF] This is some text [PDF]<h1> tags with # and remove any </h1> tags.<h1>This is a heading</h1> → # This is a headingException:
invalid type