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

Time:02-12

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!!

Desired Hotel Occupancy Program

CodePudding user response:

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)

CodePudding user response:

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]}.")

CodePudding user response:

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)
  • Related