0

I have this code (I know why it's wrong I just don't know how I could fix it)

import random

x = 0

for i in range(100):
    print(x + (random.randint(1, 6)))

Please could somebody help or point me in the right direction. Thanks in advance.

mintymoes
  • 25
  • 4

5 Answers5

2

You don't add up numbers:

import random

x = 0
for i in range(100):
    x += random.randint(1, 6)
    print(x)
Daniel
  • 42,087
  • 4
  • 55
  • 81
1

Here's the answer.

import random
x = sum([random.randint(1,6) for i in range(100)])
Berk Olcay
  • 161
  • 11
1

If you only want the final sum:

from random import randint

x = 0
for i in range(100):
    x += randint(1, 6)
print(x)

Eden Yosef's answer is the best to do the same thing in Python since it uses comprehension but I wanted to add this incase you haven't gotten to comprehension yet.

Daniel's will print every time it sums, which is how you formatted yours.

gr8t1
  • 28
  • 5
1

The previous two answers lack an explanation, so here it is:

In your code, you are adding the random number - but the problem is, you are not adding that random number to x itself, but just printing out x plus the random number. This means your loop is doing this:

print(0 + random.randint(1, 6))
print(0 + random.randint(1, 6))
print(0 + random.randint(1, 6))
# ...

Basically, x is always 0. In order to fix this, you would have to add the random number to x itself, and then print x. Additionally, you don't want to print every time you add, but once at the end - so take the print outside of the for loop:

import random

x = 0

for i in range(100):
    x += random.randint(1, 6)
print(x)

However, this can also be solved using generator comprehensions:

import random
x = sum(random.randint(1, 6) for i in range(100))
print(x)
Ayush Garg
  • 2,234
  • 2
  • 12
  • 28
0
import random

x = sum([random.randint(1,6) for i in range(100)])
print(x)
Eden Yosef
  • 39
  • 4