简体   繁体   中英

Why doesn't the value of my boolean change in a while-loop?

My algorithms book has an implementation of a linked list on Python with different methods. This is the remove method, but I don't fully understand the while loop.

This implementation relies on a Node class that was previously define, the class has methods such as get.data() , get.next() , set_next() , etc. The list itself is a class called UnorderedList . self.head refers to the first item in the list.

The idea of this remove method is to traverse the list until we find the item that we want to remove. We create a current and a previous to keep track of the current item we are looking at and the one that came before.

My question has to do with the while loop. We set found to False with the intention of changing it when we find the item we are looking for. However, wouldn't the while loop change the value of found to True when we say not found ?

I know it's a simple question, but I am having a hard time understanding why and how this while loop works since in my head not usually makes the boolean in its scope the opposite of what it is. Could anyone explain this to me?

btw I don't need any explanation or improvement on the current code, it's an example from the book and it all makes sense to me, I just want to understand that part.

def remove(self, item):
 current = self.head
 previous = None
 found = False
 while not found:
      if current.get_data() == item:
           found = True
      else:
           previous = current
           current = current.get_next()

 if previous == None:
      self.head = current.get_next()
 else:
      previous.set_next(current.get_next())

So it seems like I was missing part of the point of what the while-loop was trying to do. Indeed, saying not found means that the expression evaluates to True , but in this case that doesn't stop the loop. It does exactly what we want it to, it continues to run the loop. Once we find the item we are looking for, we change the value of found to be True . At that point, when we evaluate while not found it will yield False , which will get us out of the loop.

not found is used as a conditional in the while loop, not as a statement that changes the value. You can read while not found as while found == False

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