如何在for循环中存储变量以在循环完成后打印?



我目前正在研究一个代码,用于确定一家 8 层和每层 30 间客房的酒店的楼层入住率。我已经成功创建了循环来确定每个楼层的入住率,但是,在 for 循环完成后,我应该显示所有楼层占用率和酒店总入住率。你们有什么建议吗?希望对我想要实现的目标的描述足够好。我附上了一张所需程序应该如何运行的图片。提前谢谢你!!

print("this program will calculate a hotel's occupancy rate.")
# variable initialization
roomsOccupied = 0
floorOcupancyRate = (roomsOccupied/30) * 100
totalRoomsOccupied = 0
roomsAvailable = 30
floorOccupancyList = []
# list {1, 2, 3, 4, 5, 6, 7, 8}
# range 
# user Input
for floorNbr in {1, 2, 3, 4, 5, 6, 7, 8}:
print('Current floor: ', floorNbr)
roomsOccupied = int(input('Please enter the number of rooms occupied on this floor: '))
if roomsOccupied == True:
if roomsOccupied <= roomsAvailable:
floorOccupancyList.append(roomsOccupied)
floorOccupancyRate = round((roomsOccupied/30)*100, 2)
totalRoomsOccupied += roomsOccupied
totalOccupancyRate = round((totalRoomsOccupied/240)*100, 2)
print('For floor ', str(floorNbr), 'there are a total of ', str(roomsOccupied), 'for a floor occupancy rate of ', str(floorOccupancyRate), '%')
else:
print('Invalid occupancy amouont. Please try again.')
else:
roomsOccupied =int(input('Please enter a valid room occupacy amount: '))
print('There are a total of ', totalRoomsOccupied, 'rooms occupied for a total hotel occupancy rate of ', totalOccupancyRate, '%')
print(floorOccupancyList)
# Processing
# output
print('The total number of rooms occupied is: ', totalRoomsOccupied)

您可以采用以下方法。

# A List to store Results
res:list = []
# Loop Operation
for i in range(20):
floor = f'floor-{i}'
res.append({floor: i})
print(res)

所以我会将这些信息存储在字典中,然后使用其密钥访问它。

dict_occupied = {}
for f in floors:
occupied = input(int()) # or however you're capturing this data
dict_occupied[f] = occupied
for d in dict_occupied:
print(f"Floor {d}: Rooms occupied = {dict_occupied[d]}.")

你必须在循环之前初始化你的变量,并在循环中修改它。

例如:

floors = []
for i range(8):
floors.append(input("Please enter the rooms occupied for floor:"))
print (floors)

相关内容

  • 没有找到相关文章

最新更新