0

So I want to save a variable from my loop but when it restarts it changes the variable

print('Dice script')
for i in range(3):
  print('Rolling')
  time.sleep(1)
  droll = (randint(1, 6))
  sdroll = str(droll)
  print('Dice rolled '+ sdroll)
  time.sleep(3)
add = (Here I want to add up the variables that i got from the three loops)
print(add)

so that I get the variable droll all three times

2 Answers 2

3

Use a list to save sdroll values on each iteration, this way:

sdroll_list= []
print('Dice script')
for i in range(3):
    print('Rolling')
    time.sleep(1)
    droll = (randint(1, 6))
    sdroll = str(droll)
    sdroll_list.append(sdroll)
    print('Dice rolled '+ sdroll)
    time.sleep(3)
add_string = ' '.join(sdroll_list)) #Concatenate the strings in sdroll_list
add_values = sum(map(int, sdroll_list)) #Sum values converted from sdroll_list
print(add)

EDIT:

If you want to sum the values of droll of each iteration, do it as below:

print('Dice script')
sum_droll = 0
for i in range(3):
    print('Rolling')
    time.sleep(1)
    droll = (randint(1, 6))
    sum_droll += droll #sum droll values
    sdroll = str(droll)
    print('Dice rolled '+ sdroll)
    time.sleep(3)
print(sum_droll)
Sign up to request clarification or add additional context in comments.

2 Comments

@Joshuas_cool ... Is your purpose is to find total sum of droll ?
Yes and Thank you I was confused I thought that once the loop changes the variable you could not get it back. Thx
1

If all you need is the sum and you don't need to know what the individual outcomes were, you could sum them in the loop itself.

sdroll_sum = 0
print('Dice script')
for i in range(3):
    print('Rolling')
    time.sleep(1)
    droll = (randint(1, 6))
    sdroll_sum += droll
    print('Dice rolled '+ str(droll))
    time.sleep(3)
print(sdroll_sum)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.