0

I just want an extra roll if the dice came 6, and I want to count how many extra rolls I got.

import random

n_trails = 10    # this is not updating why?
dice = [ 1, 2, 3, 4, 5, 6 ]
got = []
extra_roll = 0   # also check this

def main():
    global n_trails
    
    n_events = 0
    
    for i in range( n_trails ):
        outcome = roll_dice()
        got.append( outcome ) 
        
        if is_event( outcome ):
            got.append("won")
                
            n_trails = n_trails + 1
        
            n_events += 1
            
            pr_e = n_events / n_trails
            print( f'after {n_trails} trails')
            print( 'P(E) = ', pr_e)
            
        
def is_event( result ):
    # was it a 6?
    return result == 6
        

def roll_dice():
    return random.choice( dice )



# ---------------------
# test 1

main()
print( got ) # total 6 you got
print( extra_roll )
# ---------------------
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50

1 Answers1

1

range(n_trails) creates a new object (of type range) that is independent of any later changes to the value of n_trails.

Instead of a for loop, use a while loop that accesses n_trails directly.

def main():
global n_trails

n_events = 0

while len(got) < n_trails:
    outcome = roll_dice()
    got.append( outcome ) 
    
    if is_event( outcome ):
        got.append("won")
            
        n_trails = n_trails + 1
    
        n_events += 1
        
        pr_e = n_events / n_trails
        print( f'after {n_trails} trails')
        print( 'P(E) = ', pr_e)
        
chepner
  • 497,756
  • 71
  • 530
  • 681