
在许多建筑中,大堂层通常被标识为0层,而非传统的1层。当我们构建一个模拟电梯系统时,往往需要使其符合这种现实世界的约定。假设我们有以下python电梯模拟代码,它能够控制电梯上下移动并打印当前楼层:
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 # 初始楼层设置为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.')这段代码在初始设定 currentFloor = 1 时工作正常。然而,当尝试将其改为 currentFloor = 0 时,一些开发者可能会遇到困惑,认为需要修改 goUpfloor 或 goDownfloor 函数内部的逻辑。实际上,原有的循环和打印机制已经足够灵活,可以自然地适应0层起始。
要使电梯模拟从0层(大堂)开始,并正确处理所有楼层,我们只需对代码进行一个简单的修改:将 currentFloor 的初始值从 1 改为 0。
currentFloor = 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 = 0 # 核心修改:初始楼层设为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.')为什么仅仅修改 currentFloor = 0 就能奏效,而不需要改动 goUpfloor 或 goDownfloor 函数内部的逻辑呢?这主要得益于Python range() 函数的特性以及代码中巧妙的打印条件。
立即学习“Python免费学习笔记(深入)”;
以 goUpfloor(0, 3) 为例,目标是从0层上升到3层:
可以看到,current += 1 操作先于打印,因此 print(f"current floor is {current}.") 总是显示电梯即将抵达或已经抵达的下一层。当 floor 达到 target - 1 时,表示这是 range 中的最后一个迭代值,此时 current 已经更新为 target,因此打印 "Arrived at..." 是正确的。
以 goDownfloor(3, 0) 为例,目标是从3层下降到0层:
同样,current -= 1 操作先于打印,print(f"current floor is {current}.") 显示的是电梯下降后的当前层。当 floor 达到 target + 1 时,表示这是 range 中的最后一个迭代值,此时 current 已经更新为 target,打印 "Arrived at..." 也是正确的。
通过这个案例,我们看到,有时一个看似复杂的需求(如将起始楼层改为0)可以通过对现有代码的深入理解和微小调整来解决,而无需进行大规模的重构。这种对代码逻辑的精确把握是编写高效、可维护程序的关键。
以上就是Python电梯模拟:实现从0层(大堂)开始的楼层控制的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号