首页 > 解决方案 > 为什么我的 If/Else 循环会脱离我的 For 循环?

问题描述

我正在做一个朋友给我的一个简单的 python 挑战,涉及电梯及其运动背后的逻辑。一切都很顺利,直到我不得不写下如何确定电梯是否可以在前往下一个排队楼层的途中撞到被叫楼层。

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()

所以在 For 循环中,有一个嵌套的 If/Else 循环,我假设它会与 for 循环中的其余代码一起迭代。但是,当我运行代码时,在到达 If/Else 循环时,它会跳出 For 循环并继续其愉快的方式,而忽略需要在数组中完成的任何进一步迭代。这里发生了什么?

当我使用一组基本的试验楼层运行代码时,这就是我得到的输出。

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

标签: pythonpython-3.x

解决方案


提前退出的原因是您在循环时修改列表。举一个简单的例子:

l = [3,6,9,10]

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

输出是

3
9

但是,您当前的代码还有许多其他问题。我能抓住的一些是:

  1. 您没有在for循环内添加新调用的楼层。
  2. floorCompare方法被queue[0]作为目标调用,而这不是最后一个。如您所见,由于您比较和,7因此没有考虑在途中。你应该比较最远的和。36310

另请注意,queue最初没有排序,中间调用也不会按顺序排列。因此,您在使用它时需要牢记这一点。


推荐阅读