如何从循环中保存变量并稍后将其恢复

时间:2016-01-01 20:21:15

标签: python

所以我想从循环中保存一个变量但是当它重新启动它时会改变变量

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)

这样我三次得到变量droll

2 个答案:

答案 0 :(得分:3)

使用列表在每次迭代中保存sdroll值,这样:

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)

修改

如果您想sum每次迭代的droll值,请按以下步骤操作:

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)

答案 1 :(得分:1)

如果您需要的只是总和,并且您不需要知道个别结果是什么,您可以在循环本身中将它们相加。

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)