Why does my If/Else loop break out of my For loop?

I'm doing a supposedly simple python challenge a friend gave me involving an elevator and the logic behind its movements. Everything was going well and good until I got to the point where I had to write how to determine if the elevator could move hit a called floor en route to its next queued floor.

def floorCompare(currentFloor,destinationFloor,calledFloor):
    if calledFloor > currentFloor and calledFloor < destinationFloor:
        return(True)
    elif calledFloor < currentFloor and calledFloor > destinationFloor:
        return(True)
    else:
        return(False)

floor = "1"
doors = "closed"
queue = []
def elevator(): # function defines how the elevator should move
    print("The Elevator is on floor: 1. The doors are "+doors+".")
    for x in range(int(input("How many floors need to be visited? "))):
        callFloor = int(input("Floor to call the elevator to: "))
        queue.append(callFloor)
        if callFloor > 10 or callFloor < 1:
            raise Exception(str(callFloor)+" is not a valid floor.")
    if queue[0] == 1:
        del queue[0]
        print("The elevator has arrived on floor 1, and the doors are open.")
    print("The queue of floors to visit is...",queue)
    for x in queue:
        print("The elevator's doors are closed and it's moving to floor:",x)
        floor = str(x)
        print("...")
        print()
        print("The elevator has arrived on floor "+floor+", and the doors are open.")
        queue.remove(x)
        addFloor = int(input("Floor to call the elevator to: "))
        if addFloor > 10 or addFloor < 1:
            raise Exception(str(addFloor)+" is not a valid floor.")
        print(queue)
        if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
            print("The elevator can hit this stop en route to its next one.")
        else:
            print("The elevator must hit this stop separately.")
    print("Continuing Queue")

elevator()

So in the For loop, there is a nested If/Else loop, which I would assume would be iterated along with the rest of the code in the for loop. However, when I run the code, upon reaching the If/Else loop, it breaks out of the For loop and continues on its merry way, disregarding any further iterations that need to be done in the array. What's going on here?

When I run the code with a basic trial set of floors, here's what I get as output.

The Elevator is on floor: 1. The doors are closed.
How many floors need to be visited? 4
Floor to call the elevator to: 3
Floor to call the elevator to: 6
Floor to call the elevator to: 9
Floor to call the elevator to: 10
The queue of floors to visit is... [3, 6, 9, 10]
The elevator's doors are closed and it's moving to floor: 3
...

The elevator has arrived on floor 3, and the doors are open.
Floor to call the elevator to: 7
[6, 9, 10]
The elevator must hit this stop seperately.
The elevator's doors are closed and it's moving to floor: 9
...

The elevator has arrived on floor 9, and the doors are open.
Floor to call the elevator to: 3
[6, 10]
The elevator must hit this stop separately.

Process finished with exit code 0

Upvotes: 0

Views: 105

Answers (3)

shriakhilc
shriakhilc

Reputation: 3000

The reason for the early exit is because you are modifying the list while looping on it. To have a simple example:

l = [3,6,9,10]

for x in l:
    print(x)
    l.remove(x)

The output is

3
9

However, there are many other problems with your current code. Some I could catch are:

  1. You aren't adding the newly called floors inside the for loop.
  2. The floorCompare method is being called with queue[0] as the destination, while that isn't the final one. As you can see, 7 was not considered en route since you compared 3 and 6. You should have compared 3 and 10, the farthest one.

Also note that queue is not initially sorted, and the intermediate calls will also not be in order. So you need to keep that in mind while using it.

Upvotes: 3

Krishna
Krishna

Reputation: 481

The reason for it to skip floor 6, is because of removing the data from the list, which is being iterated.

l=[3,6,9,10,14]
for i in l:
    print(i)

Output: 3 6 9 10 14

for i in l:
    print(i)
    l.remove(i)

output: 3 9 14

Upvotes: 0

Ethan Tang
Ethan Tang

Reputation: 16

I think your problem lies in the use of a for loop in conjunction with the queue.remove() function. It seems like the for x in queue: operator runs into problems when you edit the list while it runs. I would recommend using while queue: instead and setting x to the first element.

    while queue:
        x = queue[0]
        print("The elevator's doors are closed and it's moving to floor:",x)
        floor = str(x)
        print("...")
        print()
        print("The elevator has arrived on floor "+floor+", and the doors are open.")
        queue.remove(x)
        addFloor = int(input("Floor to call the elevator to: "))
        if addFloor > 10 or addFloor < 1:
            raise Exception(str(addFloor)+" is not a valid floor.")
        print(queue)
        if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
            print("The elevator can hit this stop en route to its next one.")
        else:
            print("The elevator must hit this stop separately.")

Upvotes: 0

Related Questions