-3

The result of this function is too small. I'm not sure where the problem is or how to fix it. Please address both

def get_n_numbers(n):
    ''' Return the sum of n random numbers from 1 through 4'''
    import random
    total = 0
    for i in range(n):
        mynumber = random.randint(1,4)
        total = total + mynumber

return total

Ellie Garmon
  • 7
  • 1
  • 3
  • 4
    Because you have `return total` _inside_ a `for` loop. Take it out of the loop. Your function breaks out immediately when it hits a `return` so you never get more than 1 iteration. – roganjosh Jun 10 '19 at 14:14

3 Answers3

0

Just move the return outside the loop, so that the function doesn't stop and return after the first pass of the loop:

def get_n_randoms(n):
    ''' Return the sum of n random numbers from 1 through 4'''
    import random
    total = 0
    for i in range(n):
        mynumber = random.randint(1,4)
        total = total + mynumber
    return total

sum_of_10 = get_n_randoms(10)
print(sum_of_10)
ruohola
  • 21,987
  • 6
  • 62
  • 97
0

Your function is returning on the first loop iteration. So move the return outside of the for loop block to return the actual total sum of all loops.

def get_n_randoms(n):
    ''' Return the sum of n random numbers from 1 through 4'''
    import random
    total = 0
    for i in range(n):
        mynumber = random.randint(1,4)
        total = total + mynumber
    return total   # < ---- right here see how it aligns with the start of the function block
William Bright
  • 535
  • 3
  • 7
0

Your return is inside your for loop so your not hitting more than one iteration.