Home > Net >  How to call upon values in a nested loop?
How to call upon values in a nested loop?

Time:10-30

I'm working on my first exam for my programming class. I can't figure out how to call upon and sum the values of a given index in a nested loop. I need to sum the wage of each employee together as well as the hours of each employee together. These values are nested as [record] in [employee_records], as index 2 and 3, respectively. Any help would be greatly appreciated!

here's the error I'm getting:

line 54, in <module>
    for y in record[2]:
TypeError: 'float' object is not iterable

code is as follows:

    num_employees = int(input("Enter number of salespersons to be evaluated: "))
numNums = num_employees
employee_records = []
wage = None
lrange = [1, 2, 3, 4]
while num_employees > 0:
    record = []
    name = (input("Enter employee name: "))
    try:
        level = int(input("Enter this employee's level: "))
        if level not in lrange:
            print("Employee level must be from 1 to 4.  Please re-enter employee's name.")
            if numNums < num_employees:
                num_employees  = 1
            continue
    except ValueError:
        print("Employee level must be from 1 to 4.  Please re-enter employee's name.")
        if numNums < num_employees:
            num_employees  = 1
        continue

    try:
        hours = float(input("Enter hours worked by this employee: "))
    except ValueError:
        print("Entry must be a number.  Please re-enter employee's name.")
        if numNums < num_employees:
            num_employees  = 1
        continue

    try:
        sales = float(input("Enter revenue generated by this employee: "))
    except ValueError:
        print("Entry must be a number.  Please re-enter employee's name.")
        if numNums < num_employees:
            num_employees  = 1
        continue
    num_employees -= 1

    record.append(name.capitalize())
    record.append(level)
    record.append(hours)
    record.append("${:,.2f}".format(sales))
    employee_records.append(record)

print(employee_records)
totalsales = None
totalhours = None
for x in employee_records:
    for y in record[2]:
        totalhours  = y
    for y in record[3]:
        totalsales  = y
print(totalhours)
print(totalsales)

CodePudding user response:

You don't need a nested loop. Just use the fields directly. However, you should NOT be formatting the sales as a string. You need the raw number in order to do math. Format it when you print it, not before.

    record.append(name.capitalize())
    record.append(level)
    record.append(hours)
    record.append(sales)
    employee_records.append(record)

print(employee_records)
totalsales = None
totalhours = None
for x in employee_records:
    totalhours  = record[2]
    totalsales  = record[3]
print(totalhours)
print(totalsales)
  • Related