简体   繁体   English

为什么 else 语句不起作用而不是 if (所有以前的情况都不正确)?

[英]Why doesn't else statement work instead of if (all previous cases aren't true)?

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.所以我有一个表示内存的列表mem ,在这个循环中,我正在搜索dataSize内存中表示为“-”的空格数。
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 .首先搜索“-” (空槽),然后将其标记为起始位置writeStart ,然后查看在该位置之后还有多少空槽并将其计为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.如果找到足够的插槽,则将Found设置为 True,否则循环中断并返回到原始循环,搜索另一个空插槽作为writeStart 。然后我使用writeStartwriteSize作为参数在此循环后写入内存。
This code works correctly but if I switch third if statement with an else it won't work anymore.这段代码工作正常,但如果我用else切换第三个if语句,它将不再起作用。 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.如果“第三个 if”是指同时具有mem[j]条件和writeSize条件的writeSize ,问题是else子句只能替代writeSize == dataSize if,而不是两者。

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.因为检查writeSize只有在增加它时才重要。

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您需要使用 elif - 链接上很好地解释了原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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