Home > Software design >  instead of using all these if statements how can I add to the total?
instead of using all these if statements how can I add to the total?

Time:05-01

simulating dice rolls and adding incremental when condition is met

instead of using all these if statements how can I add to the total (petals) as an incremental value?

I tried while loop but didn't seem to work, this seems like the only thing I could get to work.

'''

petals = 0

if die1 == 3:
    petals  = 2
if die2 == 3:
    petals  = 2
if die3 == 3:
    petals  = 2
if die4 == 3:
    petals  = 2
if die5 == 3:
    petals  = 2

if die1 == 5:
    petals  = 4
if die2 == 5:
    petals  = 4
if die3 == 5:
    petals  = 4
if die4 == 5:
    petals  = 4
if die5 == 5:
    petals  = 4

'''

I have this but petals remains as 0,

importing dice display from another file if this makes a difference?

'''

import dice 
import random 

diceRoll = ['die1', 'die2', 'die3', 'die4', 'die5']
increments = {3: 2, 5: 4} 
petals = 0 

die1 = int(random.randint(1,6)) 
die2 = int(random.randint(1,6)) 
die3 = int(random.randint(1,6)) 
die4 = int(random.randint(1,6)) 
die5 = int(random.randint(1,6)) 

for die in diceRoll: 
    petals  = increments.get(die, 0) 

dice.display_dice(die1, die2, die3, die4, die5) 
print(petals)

'''

CodePudding user response:

I would save the dice in a list and the increment values in a dictionary. Then, you can generate the number of petals by using a for loop with .get() to access values in the dictionary:

dice = [die1, die2, die3, die4, die5]
increments = {3: 2, 5: 4}
petals = 0

for die in dice:
    petals  = increments.get(die, 0)    

CodePudding user response:

try this:

petals = 0
dice = [int(random.randint(1,6)) for i in range(1, 6)]
if any([die==3 for die in dice]):
    petals  = 2
if any([die==5 for die in dice]):
    petals  = 4
  • Related