Skip to the content

Enum

Python · Unit 14: Modern classes

Some data can only take a handful of values: the status of an order, the colour of a traffic light. With loose strings, a misspelled "pad" warns you about nothing.

An Enum gives them names. Each member has its name, the name in capitals, and its value, the data you gave it.

from enum import Enum

class Status(Enum):
    NEW = 1
    PAID = 2

s = Status.NEW
print(s)
print(s.name, s.value)

Prints

Status.NEW
NEW 1

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Complete it to create the options of the traffic light.

  2. 2. Predict the output

    What does this code print?

  3. 3. Predict the output

    What does this code print?

  4. 4. Multiple choice

    What do you gain by using an Enum instead of loose strings like "paid"?

  5. 5. Find the bug

    The order is paid, so it should print Ready to ship. Which line has the error?

  6. 6. Predict the output

    What does this code print?

  7. 7. Complete the code

    Two adults and one child. Complete it so it prints 230.

  8. 8. Put the lines in order

    Put the lines in order so it prints, in this order: GOLD 3 and then SILVER 1

  9. 9. Complete the code

    Complete it to print the cost of express shipping, 120.

  10. 10. Predict the output

    An Enum also works as a field of a @dataclass. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →