Python列表应用问题:如何避免无效员工级别输入占用循环计数(附作业场景说明)
Hey there! Let's tackle your problem step by step, starting with the loop issue you're stuck on, then address your dictionary question and add some extra tips for your assignment.
Your current approach of incrementing num_employees when input fails won't work—because range(num_employees) generates a fixed sequence when the loop starts. Even if you change num_employees later, the for loop will only run the original number of times.
Instead, use a while loop with a counter to control how many valid employee records you collect. This way, invalid inputs don't "use up" a slot. Here's a revised version of your code with this fix, plus better input validation for each field:
num_employees = int(input("Enter number of salespersons to be evaluated: ")) employee_records = [] valid_levels = [1, 2, 3, 4] count = 0 # Track how many valid records we've collected while count < num_employees: record = [] name = input("Enter employee name: ") # Validate level input (loop until valid) level = None while level not in valid_levels: try: level = int(input("Enter this employee's level: ")) if level not in valid_levels: print("Employee level must be from 1 to 4.") except ValueError: print("Employee level must be an integer from 1 to 4.") # Validate hours input hours = None while hours is None: try: hours = float(input("Enter hours worked by this employee: ")) except ValueError: print("Entry must be a number.") # Validate sales input sales = None while sales is None: try: sales = float(input("Enter revenue generated by this employee: ")) except ValueError: print("Entry must be a number.") # Only add the record and increment count if all inputs are valid record.append(name) record.append(level) record.append(hours) record.append(sales) employee_records.append(record) count += 1 print(employee_records)
Each input field uses its own small while loop to keep asking until the user enters valid data. The main counter count only increments when we have a complete, valid record—so invalid inputs don't eat into your total employee count.
Since your course hasn't covered dictionaries yet, stick with nested lists! Your instructor almost certainly expects you to use the tools you've already learned. Nested lists are totally appropriate here—you can access each employee's data via indexes (e.g., record[0] for name, record[1] for level) when you calculate commissions and wages later.
Once you have valid records, you can integrate your commission and wage functions to compute the required outputs:
- Calculate totals (total sales, total commission, total wages) by iterating over
employee_records - Format your output to be readable (instead of printing the raw list)
Example snippet for output:
# Assume you have these functions defined: def calculate_commission(level, sales): # Your commission logic here if level == 1: return sales * 0.05 # ... add other levels return 0 def calculate_wage(hours): # Your wage/OT logic here regular_rate = 15 ot_rate = regular_rate * 1.5 if hours <= 40: return hours * regular_rate else: return (40 * regular_rate) + ((hours - 40) * ot_rate) # Print summary totals total_sales = sum(record[3] for record in employee_records) total_commission = sum(calculate_commission(record[1], record[3]) for record in employee_records) total_wages = sum(calculate_wage(record[2]) for record in employee_records) print("\n=== Sales Team Summary ===") print(f"Total Sales: ${total_sales:.2f}") print(f"Total Commission Paid: ${total_commission:.2f}") print(f"Total Wages (including OT): ${total_wages:.2f}") # Print individual employee details print("\n=== Individual Employee Breakdown ===") for record in employee_records: name = record[0] commission = calculate_commission(record[1], record[3]) total_pay = calculate_wage(record[2]) + commission print(f"\nName: {name}") print(f"Personal Commission: ${commission:.2f}") print(f"Total Pay (including OT): ${total_pay:.2f}")
内容的提问来源于stack exchange,提问作者Grelm

