用python写一个电梯程序
时间: 2023-08-14 22:05:38 浏览: 75
好的,以下是一个简单的电梯程序,使用Python实现:
```python
class Elevator:
def __init__(self, floors=10):
self.floors = floors
self.current_floor = 1
self.direction = "up"
self.destination_floors = set()
self.stops_made = 0
def move(self):
if not self.destination_floors:
return
if self.direction == "up":
self.current_floor += 1
else:
self.current_floor -= 1
if self.current_floor in self.destination_floors:
self.destination_floors.remove(self.current_floor)
self.stops_made += 1
print(f"Stopped at floor {self.current_floor}")
if not self.destination_floors:
self.direction = "up" if self.current_floor == 1 else "down"
def add_destination(self, floor):
if floor > self.floors or floor < 1:
print("Invalid floor number.")
return
if floor == self.current_floor:
print("Already on this floor.")
return
self.destination_floors.add(floor)
if floor > self.current_floor:
self.direction = "up"
else:
self.direction = "down"
elevator = Elevator()
while True:
print(f"Current floor: {elevator.current_floor}\n")
command = input("Enter a floor number to go to or 'q' to quit: ")
if command == "q":
break
try:
floor = int(command)
elevator.add_destination(floor)
except ValueError:
print("Invalid input.")
continue
while elevator.destination_floors:
elevator.move()
```
这个程序模拟了一个电梯,可以接受用户输入的目标楼层,并将电梯移动到目标楼层。当电梯到达一个目标楼层时,它会停下来,然后等待下一个目标楼层的输入。程序会不断运行,直到用户输入“q”退出。