So I have a list mem that represents memory and in this loop I'm searching for dataSize number of empty spaces which are represented as "-" in memory.
Logic is following:
First search for "-" (empty slot), then mark it as starting location writeStart and then see how much more empty slots I have after that position and count it as writeSize . Found is then set on True if I have found enough slots or else loop breaks and returns to original loop that searches for another empty slot as writeStart .Then I use writeStart and writeSize as parameters to write in memory after this loop.
This code works correctly but if I switch third if statement with an else it won't work anymore. Why? Thank you in advance.
for i in range(len(mem)):
if(mem[i] == "-"):
writeStart = i
writeSize = 0
for j in range(i, len(mem)):
if(mem[j] == "-"):
writeSize += 1
if(writeSize == dataSize):
found = True
break
if((mem[j] != "-") & (writeSize != dataSize)): #if switched with an else: error
i = j
break
if(found):
break
If by "third if" you mean the one that has both the mem[j]
condition and the writeSize
condition, the problem is that the else
clause would only be the alternative to the writeSize == dataSize
if, not to both of them.
I think you could restructure the code like this:
for j in range(i, len(mem)):
if (mem[j] == "-"):
writeSize += 1
if (writeSize == dataSize):
found = True
break
else:
i = j
break
because checking writeSize
only matters if you increment it.
I think you can refer to this link :
What's the main difference between 'if' and 'else if'?
You need to use elif - the reason is explained well on the link
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.