You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python电梯模拟代码以支持0层(大堂层)作为起始层

电梯模拟代码修改:起始层改为0层

原代码

def goDownfloor(current, target):
    for floor in range(current, target, -1):
        current -= 1
        if floor != target+1:
            print(f"current floor is {current}.")
        else:
            print(f"Arrived at the {target} . Goodbye.")
    return current

def goUpfloor(current, target):
    for floor in range(current, target):
        current += 1
        if floor != target-1:
            print(f"current floor is {current}.")
        else:
            print(f"Arrived at the {target} . Goodbye.")
    return current

currentFloor = 1
while(True):
    targetFloor = int(input("Enter the floor you want to go to (enter -100 for outages):"))
    if targetFloor == -100:
        break
    else:
        if targetFloor > currentFloor:
            currentFloor = goUpfloor(currentFloor, targetFloor)
        elif targetFloor < currentFloor:
            currentFloor = goDownfloor(currentFloor, targetFloor)
        elif targetFloor == currentFloor:
            print('Please re-enter another floor.')

需求与问题

要保留代码原有逻辑,把电梯起始层改成0层(大堂层),比如输入目标3层时,能正确显示完整的到达过程。但直接把currentFloor设为0后运行失败,调整current +=1上方的起始层设置也没用。

解决方法

其实你不用改动函数内部的逻辑,只需要修改起始层的初始值就行。之前运行失败大概率是误改了函数里的代码,或者测试时输入了不符合预期的楼层(比如负数)。以下是修正后的完整代码:

def goDownfloor(current, target):
    for floor in range(current, target, -1):
        current -= 1
        if floor != target+1:
            print(f"current floor is {current}.")
        else:
            print(f"Arrived at the {target} . Goodbye.")
    return current

def goUpfloor(current, target):
    for floor in range(current, target):
        current += 1
        if floor != target-1:
            print(f"current floor is {current}.")
        else:
            print(f"Arrived at the {target} . Goodbye.")
    return current

# 仅修改这一行,把起始层设为0
currentFloor = 0
while(True):
    targetFloor = int(input("Enter the floor you want to go to (enter -100 for outages):"))
    if targetFloor == -100:
        break
    else:
        if targetFloor > currentFloor:
            currentFloor = goUpfloor(currentFloor, targetFloor)
        elif targetFloor < currentFloor:
            currentFloor = goDownfloor(currentFloor, targetFloor)
        elif targetFloor == currentFloor:
            print('Please re-enter another floor.')

测试示例

输入目标3层时,运行输出如下:

Enter the floor you want to go to (enter -100 for outages):3
current floor is 1.
current floor is 2.
Arrived at the 3 . Goodbye.

完全符合需求。如果输入的目标层和当前层(0层)一致,代码会提示重新输入;如果输入-100,程序退出,这些逻辑都正常。

内容的提问来源于stack exchange,提问作者황지현

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:22:46