Pure Programmer

Enumerations

Enums1.py
```#!/usr/bin/env python3;
from enum import Enum, auto
import Utils

class CompassPoint(Enum):
NORTH = auto()
EAST = auto()
SOUTH = auto()
WEST = auto()

def CompassPointToString(c) :
result = ""
for case in Utils.switch (c) :
if case(CompassPoint.NORTH) :
result = "North"
break
if case(CompassPoint.EAST) :
result = "East"
break
if case(CompassPoint.SOUTH) :
result = "South"
break
if case(CompassPoint.WEST) :
result = "West"
break
return result

def turnRight(c) :
if (c == CompassPoint.NORTH) :
return CompassPoint.EAST
elif (c == CompassPoint.EAST) :
return CompassPoint.SOUTH
elif (c == CompassPoint.SOUTH) :
return CompassPoint.WEST
else :
return CompassPoint.NORTH

# Begin Main
cp1 = CompassPoint.NORTH
print("cp1: " + str(cp1))
print("SOUTH: " + CompassPointToString(CompassPoint.SOUTH))
print("turnRight(cp1): " + CompassPointToString(turnRight(cp1)))
cp2 = CompassPoint.EAST
if (cp1 == cp2) :
print("cp1 == cp2")
else :
print("cp1 != cp2")
cp1 = cp2
if (cp1 == cp2) :
print("cp1 == cp2")
else :
print("cp1 != cp2")

```
Output
\$ python3 Enums1.py cp1: CompassPoint.NORTH SOUTH: South turnRight(cp1): East cp1 != cp2 cp1 == cp2
Enums2.py
```#!/usr/bin/env python3;
from enum import Enum, auto
import Utils

class Color(Enum):
RED = 1
GREEN = 2
YELLOW = 3
BLUE = 4
MAGENTA = 5
CYAN = 6

def combineColors(c1, c2) :
i1 = c1.value
i2 = c2.value
result = Utils.bitwiseOr32(i1, i2)
returnColor = Color(result)
return returnColor

# Begin Main
c1 = Color.BLUE
print("c1: " + str(c1))
print("RED: " + str(Color.RED))
print("combineColors(c1, RED): " + str(combineColors(c1, Color.RED)))
c2 = Color.GREEN
print("combineColors(c1, c2): " + str(combineColors(c1, c2)))
if (c1 == c2) :
print("c1 == c2")
else :
print("c1 != c2")
c1 = c2
if (c1 == c2) :
print("c1 == c2")
else :
print("c1 != c2")

```
Output
\$ python3 Enums2.py c1: Color.BLUE RED: Color.RED combineColors(c1, RED): Color.MAGENTA combineColors(c1, c2): Color.CYAN c1 != c2 c1 == c2 Traceback (most recent call last): File "/Users/rich/Desktop/Resources/pureprogrammer/py/examples/Enums2.py", line 36, in <module> bad = Color(7) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/enum.py", line 384, in __call__ return cls.__new__(cls, value) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/enum.py", line 702, in __new__ raise ve_exc ValueError: 7 is not a valid Color
python

Questions

• {{Who's on first?}}
• {{Who's on second?}}
• {{Who's on third?}}

Projects

More ★'s indicate higher difficulty level.

References

• [[Python Language Reference]]
• [[Python Standard Library]]
• [[Python at TutorialsPoint]]