Sergio Bost
Sergio Bost

Reputation: 3209

Trying to understand python, why is this function not working? [Added formulas]

(I added the function in question @ Bottom)

Working on my first python app.

Im making a simple rock, paper, scissors game.

I have a function that takes in two parameters:

  1. The users input
  2. The computers input

The function looks like this:

seeIfUserWon(userInput, selectRandomOption()) where selectRandomOption() just chooses a random Enum (ROCK, PAPER, SCISSORS)

The code works if I replace selectRandomOption with hardcoded input.


Currently that code gives me the error:

ValueError: 'Paper' is not a valid RPS where RPS is an Enum class with 3 cases: ROCK, PAPER, SCISSORS

But like I said if I just put in RPS.ROCK for the second parameter then it works...

What am I not understanding about python.. maybe I need to use a lambda here but I'm not sure? Any references would be appreciated as well!


Functions I used:

def selectRandomOption() -> RPS:
    pick = options[random.randint(0,2)]
    return RPS(pick)

Options:

options = ["Rock", "Paper", "Scissors"]

Which I then validate with:

def validateUserInput(input):
  if "rock" in input.lower():
    return RPS.ROCK
  elif "paper" in input.lower():
    return RPS.PAPER
  elif "scissors" in input.lower():
    return RPS.SCISSORS
  else:
    raise Exception

Enum :

class RPS(Enum):
  ROCK        = auto()
  PAPER       = auto()
  SCISSORS    = auto()

Upvotes: 2

Views: 74

Answers (3)

osint_alex
osint_alex

Reputation: 1022

It's tricky to say for sure without seeing the seeifuserwon function but I think this is probably what's going on.

If you rewrite this function as below:

def selectRandomOption() -> RPS:
    pick = random.randint(1, 3)
    return RPS(pick)

I suspect that will fix your problem... You've defined RPS as an Enum class. To get the corresponding class member for a value you need to pass the number to the Enum class - details here.

I also changed it to (1, 3) in the above since the count starts from 1 not 0 in the Enum class.

Upvotes: 2

Sean
Sean

Reputation: 89

Try this:

class RPS(Enum):
  ROCK        = "Rock"
  PAPER       = "Paper"
  SCISSORS    = "Scissors"

Upvotes: 0

Mark
Mark

Reputation: 92440

Rather than randomly picking an integer, then looking up a string, then getting an enum value, consider just choosing the enum value directly. For example:

import random

class RPS(Enum):
    ROCK        = auto()
    PAPER       = auto()
    SCISSORS    = auto()

random.choice(list(RPS))
# <RPS.SCISSORS: 3>

Upvotes: 4

Related Questions