Creating dice game : NEED HELP ON CHECKING ELEMENTS IN A LIST

MRAB python at mrabarnett.plus.com
Sat Oct 6 15:44:48 EDT 2018


On 2018-10-06 19:10, eliteanarchyracer at gmail.com wrote:
> Hi, I am new to python and would like someones help on the following:
> 
> After rolling 5 dice and putting the results into a list, I need to check if any dice is not a 1 or 5.
> 
> if all dice in the list are either a 1 or 5 , I want to calculate a result.
> if there is a 2,3,4 or 6 in the list i want to let the user roll again
> FOR EXACT LINE: PLEASE CHECK CODE
> 
> 
> CODE:
> 
> 
> from random import *
> 
> class Dice:
> 
>      def __init__(self, sides, color="white"):
>          self.sides = sides
>          self.color = color
> 
>      def roll_dice(self):
>          result = randint(1, self.sides)
>          return result
> 
> 
> die1 = Dice(6)
> die2 = Dice(6)
> die3 = Dice(6)
> die4 = Dice(6)
> die5 = Dice(6)
> 
> alldice = [die1, die2, die3, die4, die5]
> 
> result = []
> 
> start = input("Press enter to roll your dice:")
> 
> for object in alldice:
>      temp = object.roll_dice()
>      result.append(temp)
> print(result)
> 
> # ----- THIS LINE IS WHERE I NEED HELP ---- # ( if 2, 3, 4, 6 in list: )
>      print("you can roll again")
> else:
>      print("you have all 1's and 5's in your result")
> 
The simplest (and longest) way is:

     if 2 in result or 3 in result or 4 in result or 6 in result:

A cleverer way is to use sets:

     if set(result) & {2, 3, 4, 6}:



More information about the Python-list mailing list