How to store variables in for-loop to print after loop has completed?

265 Views Asked by At

I am currently working on a code that determines the floor occupancy rate of a hotel with 8 floors and 30 rooms per floor. I have successfully created the loop to determine the occupancy of each floor, however, after the for loop has completed, I’m supposed to display all the floor occupancy rates and total hotel occupancy rate. Do you guys have any advice? Hopefully the description of what I’m trying to achieve is good enough. Ive attached a picture of how the desired program should run. Thank you in advance!!

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

There are 3 best solutions below

0
Rama On

You can take the following approach.

# A List to store Results
res:list = []

# Loop Operation
for i in range(20):
    floor = f'floor-{i}'
    res.append({floor: i})

print(res)
0
blanky On

So I would store this information in a dictionary, and then access it with its key.

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]}.")
0
Artem Ermakov On

You've got to initialize your variable before the loop and modify it inside the loop.

For example:

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

print (floors)