0

I'm learning Python, and decided to make a little dice game. It functions 100% as intended, just want to make some small changes to make it more polished up, such as not just ending if you input something that isn't supported.

if answer == 'y':
dice = raw_input('What sorta dice? (D4, D6, D12, D20)')
--if dice = ANYTHING THAT ISN'T A DICE
    dice = raw_input('I don't have that, try again!')--

else:
if answer == 'n':
    print 'Alright, come back anytime!'
    exit()

I just can't find an answer to the if dice = problem, I've googled for about an hour and chances are I just don't know the right terminology to ask the question properly. I basically want it to state something along the lines of "nope thats not right" then loop back up to "what sorta dice"

Cheers for any input guys.

Slappy
  • 35
  • 2
  • 8

1 Answers1

1

you could try this:

if dice not in ('D4', 'D6', 'D12', 'D20'):
    ...

and if you want to make sure things like 'd4' also get accepted:

if dice.upper() not in ('D4', 'D6', 'D12', 'D20'):
    ...

and - as mentioned by Delgan - comparing to a set not a tuple is faster even for only 4 elements (and scales way better the higher the number of elements is)

if dice.upper() not in {'D4', 'D6', 'D12', 'D20'}:
    ...
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • Best practice is to use a set: `in {'D4', 'D6', 'D12', 'D20'}` as look-up time is O(1). – Delgan Dec 24 '16 at 09:45
  • @Delgan if you mean 'best in terms of speed': not sure if `set` is quicker for 4 elements than `tuple`. but in general i agree - it *scales* better. – hiro protagonist Dec 24 '16 at 09:51
  • Yes, I mean it is better to stay with sets in the general cases, just for consistency. Even for 4 elements, [it is actually faster](http://image.noelshack.com/fichiers/2016/51/1482573733-screenshot.png). – Delgan Dec 24 '16 at 10:03
  • @Delgan: ha, thanks for the benchmark. will try to remember that. updated the (closed) question. – hiro protagonist Dec 24 '16 at 10:05