drwie
drwie

Reputation: 125

Getting string error when appending to list

I keep receiving the error message:

AttributeError: 'str' object has no attribute 'append'

in relation to line 18 (last line below). And I can't see what I'm doing wrong. I thought the code converts all items in the 'employees' list into lists themselves. So it should not be returning a string error to append to one of these items.

This is my first programme not guided by a crash course book, so apologies if the answer is blindingly obvious

employees=[]
peeps=()
hours=()
total_hours=[]
tip=()
tips=int(input("What was the total tips?: "))
print("Enter employees' names followed by enter. Press x to stop")
while peeps != 'x': #input employee names
  peeps=raw_input("Name: ")
  employees.append(peeps)
def extractEmployees(employees): #covert employees to list of lists
  return [[x] for x in [employees]]
extractEmployees(employees) #run conversion
for x in employees: #input hours worked by each employee
  print("Enter hours for ", x, "individual daily hours followed by enter, or sum of hours worked. Press x when done")
  while hours != 'x': #add hours to employee's list
    hours=int(input())
    x.append(hours)

Upvotes: 0

Views: 367

Answers (2)

Manu1800
Manu1800

Reputation: 145

extractEmployees is not set to define or change the value of employees, it only returns a list. You should do employees = extractEmployees(employees) instead of only calling the function. You are getting an AttributeError on line 18 because of the problem you had with extractEmployees, not changing employees to a list of lists, so the item that is supposed to be a list remained as a string.

Upvotes: 1

Jeremy
Jeremy

Reputation: 671

extractEmployees is run but the return value is never used, so employees is never changed. You probably want to assign the output like this: employees = extractEmployees(employees)

However, it's probably preferable to store this output in a new list, so you can still access just the employee's names.

Additionally, using lists to store different types of information like this is confusing. In this case you would probably want to use a dictionary for each employee: {'name': employee_name, 'hours': hours}

Upvotes: 2

Related Questions