Generate random numbers and add them

0

I would like to be able to make the script generate " n " numbers (so far everything is done as you can see in the code below) and add them up.

import random

n = 2

total = (random.randint(1, 100), n)

print total

Now all you need to do is add these "n" numbers.

    
asked by anonymous 04.07.2017 / 18:46

3 answers

1

Would that be what you need?

import random

n = 2

total = random.randint(1, 100) + n

print total

If you need to randomize more than 1 number and add up all the generated numbers, you can do this:

import random

total = 0;

for i in xrange(0, 2):
    numeroGerado = random.randint(1, 100)
    print numeroGerado
    total += numeroGerado

print total
    
04.07.2017 / 18:54
2

To generate n random numbers, use generators : p>

numbers = (random.randint(1, 100) for _ in range(n))
  

Note: If the list of numbers is used for more than just calculating the sum, do not use a generator, but rather list comprehension (just switch from () to [] ):

     

numbers = [random.randint(1, 100) for _ in range(n)]

Where n is the number of numbers to be generated. Note that if you do print(numbers) , the output will be:

<generator object <genexpr> at ...>

That is, the list itself has not yet been generated. Even so, to get the sum of the values, just use the native function sum :

total = sum(numbers)

By doing print(total) , an integer value referring to the sum of all numbers is displayed. In my case, the total was 300.

  

See working on Ideone .

    
04.07.2017 / 19:51
-1
import random

n = 2

total = (random.randint(1, 100), n)

a=str(total).split(",")[0].split("(")[1]
b=str(total).split(",")[1].split(")")[0]

soma=int(a) + int(b)

print soma
    
04.07.2017 / 18:55