功能结果太小。如何解决这个问题?

时间:2019-06-10 14:12:59

标签: python function

此功能的结果太小。我不确定问题出在哪里或如何解决。请同时解决

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

总回报

3 个答案:

答案 0 :(得分:0)

只需将return移到循环外,这样函数就不会在循环的第一遍之后停止并返回:

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)

答案 1 :(得分:0)

您的函数在第一次循环迭代中返回。因此,将返回值移到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 循环块之外,以返回所有循环的实际总和。

{{1}}

答案 2 :(得分:0)

您的回报位于for循环内,因此您不会遇到多次迭代。