I am practicing beginners Python projects and trying to do the dice rolling simulator, where it stores the totals of all die in a list. However, it doesn't work for some reason. Could someone explain why a code like this works:
n=0
a=[]
while n<6:
n+=1
a.append(n)
print(a)
and produces [1, 2, 3, 4, 5, 6], but this code doesn't:
import random
maxnum=6
minnum=1
roll_again="y"
count=0
while roll_again=="y":
tots=[]
print("rolling the dice...")
roll1=(random.randint(minnum,maxnum))
roll2=(random.randint(minnum,maxnum))
count+=1
total=roll1+roll2
print(roll1, roll2)
print("Try #",count, ": Total = ", total,"\n")
roll_again=input("Roll the dice again? Y/N ")
if roll_again!="y" and roll_again!="n":
print("please enter 'y' for yes or 'n' for no")
roll_again=input("Roll the dice again? Y/N ")
tots.append(total)
print(tots)
It just prints the last total as a list with one value. What am I missing here?
Move the tots = []
out of while loop, as wnnmaw suggested. Write it just before the loop, underneath count=0
.
you reset the list tots=[]
in each iteration so that it never gets to hold more than one element. try to put it outside the while loop:
tots=[]
while roll_again=="y":
...
tots.append(...)
print(tots)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.