Click here to Skip to main content
15,846,342 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I’ve been making a Payroll program, and I seem to have problems around line 86 of my code, with “IndexError: list assignment index out of range” popping up every time I run the program. Can anyone help me solve this issue please?

Python
from __future__ import annotations
from typing import List

fixed_rate_month = 1800  # Full-Time
fixed_rate_hour = 7  # Shift Worker

hours_worked = []

emp_count = 0   # TODO ARRANGE


class Employee:
    EMPLOYEES: List[Employee] = []

    def __init__(self, name: str, surname: str, emp_type: str):
        self.name: str = name
        self.surname: str = surname
        self.emp_type = emp_type
        self.__id: int = Employee.__get_next_id()
        self.__pay_details: dict = {}
        Employee.EMPLOYEES.append(self)

    @property  # This property allows read-only access to __id (getter)
    def id(self) -> int:  # This returns an int (type hint)
        return self.__id

    @property
    def pay_details(self) -> dict:
        return self.__pay_details

    @staticmethod  # This keeps just one copy of the method in the class
    def __get_next_id() -> int:
        next_id = 0
        for e in Employee.EMPLOYEES:
            next_id = e.__id if e.__id > next_id else next_id
        next_id += 1
        return next_id

    @staticmethod
    def get_by_id(employee_id: int) -> Employee:
        for e in Employee.EMPLOYEES:
            if e.__id == employee_id:
                return e


def show_menu():
    while True:
        print('\nPayroll System')
        print('---------------')
        print('1. Add an Employee')
        print('2. Show Employees')
        print('3. Exit')
        response = input('Choice >')

        if response == '1':
            add_employee()
        elif response == '2':
            show_employees()
        elif response == '3':
            pass
        else:
            print('Invalid Option!')


def add_employee():
    global emp_count

    checker = False
    print('\nAdding an Employee')
    name = input('Name >')
    surname = input('Surname >')

    emp_type = ''  # So the variable is created
    while checker is False:
        print('\nWhich type of employee is', name, surname, '?')
        print('     Full-Time Employee (FT)')
        print('     Shift Worker (SW)')
        emp_type = input(str('\nEmployment Type >'))

        if emp_type != 'FT' and emp_type != 'SW' and emp_type != 'ft' and emp_type != 'sw':
            print('Invalid Option! Please try again.')
        else:
            checker = True
            if emp_type == 'SW' or emp_type == 'sw':
                print('\nHow many hours has', name, surname, 'worked?')
                hours_worked.append(int(input('Hours >')))
                print(emp_count)

    if checker:
        # Only do this if the checker works
        Employee(name, surname, emp_type)
        emp_count += 1


def show_employees(employee_id: int) -> None:       # TODO ARRANGE LATER'
    e = Employee.get_by_id(employee_id)
    print('\n{0:3}\t{1:10}\t{2:10}\t{3:5}'.format('ID', 'Name', 'Surname', 'Emp. Type'))
    for e in Employee.EMPLOYEES:
        print('{0:03d}\t{1:10}\t{2:10}\t{3:<5.1}'.format(e.id, e.name, e.surname, e.emp_type))

    print('\nPay Details of Employee {0:03d} ({1} {2})'.format(e.id, e.name, e.surname))
    print('{0:10}\t{1:5}'.format('Gross Wage', 'Net Wage', 'Payslip Date'))
    for gross_wage, net_wage, ps_date in e.pay_details.items():
        print('{1:10}\t{1:<5}'.format(gross_wage, net_wage, ps_date))


show_menu()


What I have tried:

I'm not sure, I just messed around to try and find alternatives.
Posted
Updated 23-Aug-23 2:45am
v4
Comments
Richard MacCutchan 22-Aug-23 8:42am    
            show_employees() # you need to pass the employee id as a parameter

# ...

def show_employees(employee_id: int)

The show_employees method reqiires an employee id in the call. So either add that to the call in the menu section, or change the definition to not require an id value.

1 solution

The error message is telling you that there is no such element in the array you are assigning to:
Python
hours_worked[emp_count] = int(input('Hours >'))
And that is because the array has no elements when you start:
Python
hours_worked = []

Instead of assuming an element exists when you try to add a new employee (which is won't as you are trying to create it!) append the new employee data to the array:
Python
hours_worked.append(int(input('Hours >')))


Quote:
Hi, and thank you so much for helping!

However, as I tried this solution, another error popped up: TypeError: show_employees() missing 1 required positional argument: 'employee_id'. I have updated the code in the question, and the problem seems to be coming from line 58.


You should expect to get syntax errors every day, probably many times a day while you are coding - we all do regardless of how much experience we have! Sometimes, we misspell a variable, or a keyword; sometimes we forget to close a string or a code block. Sometimes the cat walks over your keyboard and types something really weird. Sometimes we just forget how many parameters a method call needs.

We all make mistakes.

And because we all do it, we all have to fix syntax errors - and it's a lot quicker to learn how and fix them yourself than to wait for someone else to fix them for you! So invest a little time in learning how to read error messages, and how to interpret your code as written in the light of what the compiler is telling you is wrong - it really is trying to be helpful!

So read this: How to Write Code to Solve a Problem, A Beginner's Guide Part 2: Syntax Errors[^] - it should help you next time you get a compilation error!

And spending a little time learning to understand syntax error messages will save you a huge amount of time in future: you waited at least 25 minutes for me to reply, then your email system probably added another 10 minutes or so, plus the time it took you to type up the question. Chances are that you could have saved a significant chunk of that time if you knew how to read them!

I'm not saying we don't want to help you fix them - sometimes I can't see my own errors because I read what I meant to write - but fixing syntax errors is part of the job, and if you can't do it for yourself people are going to look at you as a bit weird should you get a job in the industry!

In this case look at where you define the function and where you use it, and combine that with the error message and it should be pretty obvious what you forgot!
 
Share this answer
 
v2
Comments
CPallini 22-Aug-23 6:01am    
5.
Member 16076363 22-Aug-23 7:58am    
Hi, and thank you so much for helping!

However, as I tried this solution, another error popped up: TypeError: show_employees() missing 1 required positional argument: 'employee_id'. I have updated the code in the question, and the problem seems to be coming from line 58.
OriginalGriff 22-Aug-23 8:25am    
Answer updated.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900