Search code examples
pythonpython-2.7randomintegergenerated

How do I add the output of 8 randomly generated numbers in python?


elif a == "other":
    numberset = 0
    for count in range(8):
        nnn = randrange(33,126)
        print(nnn)
        numberset += nnn

I need to find out how to add all of the 8 generated numbers to make a total and then set that as a variable.


Solution

  • Why not

    numberset = sum(randrange(33, 126) for _ in range(8))
    

    The argument of sum is a generator expression, i.e. it produces a generator that sum can iterate on, summing all the values given.

    As you can see, I have used the _ name as the counter. It is a naming convention for those variables that are not used further (i.e. in your loop, count is never used)

    In case you want to print out the numbers as well (and keep them maybe) you can do

    numbers = [randrange(33, 126) for _ in range(8)] # list comprehension
    numberset = sum(numbers)
    for n in numbers:
        print(n)
    print('Sum is', numberset)
    

    which produces

    112
    69
    77
    33
    56
    55
    118
    65
    Sum is 585