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.
You don't add up numbers:
import random
x = 0
for i in range(100):
x += random.randint(1, 6)
print(x)
Here's the answer.
import random
x = sum([random.randint(1,6) for i in range(100)])
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.
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 comprehension
s:
import random
x = sum(random.randint(1, 6) for i in range(100))
print(x)