简体   繁体   中英

Why Isn't My If Statement Stopping This Index Error?

Very new to python and programming in general, i keep getting this index error and cant figure out why.

Im trying to build a basic simulation of a dice game i've tried adding if statements and while loops to make it so if the list is empty it wont try to append things

if dice > 0:
  if 0 <= (len(roll)):
    while roll [0] <= (always_keep):
     keeps.append(roll.pop(0))
    else:
      pass
    if (len(roll)) == (dice):
     keeps.append(roll.pop(0))
     dice = (dice - 1)
    else:
        pass

line 106, in

while roll [0] <= (always_keep):

IndexError: list index out of range

Please use consistent indentation as your else is for the while , not the if , which is most likely not what you want, and else: pass seems pointless anyway.

The problem is that the while loop body keeps pop() ping roll away to nothing, so you want:

while roll and roll[0] <= always_keep:

All the extra brackets are unnecessary.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM