0

I found this code which is supposed to illustrate how enums work. I'm aware things are differnt now in Python 3, but I want to make sense of this example. What do I need to input to get print("You chose the easy option") to execute please?

I've tried 1, Easy and Choice.Easy so far with no success.

def enum(**enums):
    return type('Enum', (), enums)

Choice = enum(Easy = 1, Medium = 2, Hard = 3)
choice = input("Enter choice: ")

if choice == Choice.Easy:
    print("You chose the easy option")
elif choice == Choice.Medium:
    print("You chose the medium option")
elif choice == Choice.Hard:
    print("You chose the hard option")
else: 
    print("You should choose one of the three levels!")
1
  • Python 2 will no longer be supported in less than one month. Do not use it. Commented Dec 5, 2019 at 12:35

3 Answers 3

2

The input which user has entered is string type and in Choice it has integer. Make change:

Choice = enum(Easy = '1', Medium = '2', Hard = '3')

or

choice = int(input("Enter choice: "))

in this case you need to handle exception valueError

Sign up to request clarification or add additional context in comments.

Comments

1

That example does not create an enum, just a class with some members that have integer values.

The reason it is not working in Python 3 is because in Python 2 input() evaled whatever was entered, so typing 1 actually returned an int; in Python 3 input became the same as Python 2's raw_input(), which returns strs and makes you do any necessary conversions.

In other words:

  • Python 2
    >>> input('give me a number: ')
    give me a number:                # enter '1' and hit <Enter>
    1                                # returns the int 1
  • Python 3
    >>> input('give me a number: ')
    give me a number:                # enter '1' and hit <Enter>
    '1'                              # returns the str '1'

For actual Enums, use either the stdlib enum module or the third-party aenum1 module (which supports advanced Enum creation as well as having Python 2 support).

An actual Enum would look like this:

from enum import Enum          # or from aenum import Enum

class Choice(Enum):
    Easy = 1
    Medium = 2
    Hard = 3

and converting user input:

choice = input("Enter choice: ")
choice = Choice(int(choice))

if choice is Choice.Easy:        # NB: use `is` instead of `==` for normal enums
    ...

1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

Comments

1

This is not working because you are comparing string with integer. you can take input as integer.

choice = int(input("Enter choice: "))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.