Question

Here's an updated version from my previous question here. I'm adding to the code where if the get_close_matches name isn't the name of the person they wanted, then discard the closest match and re-run the function and grab the second-closest match (now first, since the function would throw out the first match).

Do you have any comments on how this can be written better? And work. >.>

Here's what I have so far:

def throwout(pickedName):
    employeeNames.remove(pickedName)
    pickedName = difflib.get_close_matches(userEmpName, employeeNames, 1)
    print(pickedName)
    userNameOK = input("Is this the name of the person you're looking for?\n\n Type 'Y' or 'N'.\n\n")



employeeNames = ['Colton','Jayne','Barb','Carlene','Dick','Despina']


employeeNames.sort()


userEmpName = input("Please enter the employee name you're searching for. We'll return the best match on record.")


pickedName = difflib.get_close_matches(userEmpName, employeeNames, 1)
print(pickedName)


userNameOK = input("Is this the name of the person you're looking for?\n\n Type 'Y' or 'N'.\n\n")


if userNameOK == "N" or "n":
    if pickedName in employeeNames:
        throwout(pickedName)
    else:
        break
else:
    break

Error for running out of names in the list:

Traceback (most recent call last):
  File "C:/Python33/employee1.py", line 64, in <module>
    print(userAnswer + " is the right choice.\n")
NameError: global name 'userAnswer' is not defined

I understand that to mean that since the list of names has no more names from removing them all, the global variable "userAnswer" is then undefined.

Was it helpful?

Solution

There is no need of creating a function to throw out the names from list as list.remove(name) does the same thing in a single line.

import difflib

employeeNames = ['Colton','Coltron','Colty','Jayne','Barb','Carlene','Dick','Despina']
employeeNames.sort()
userEmpName = raw_input("Please enter the employee name you're searching for. We'll return the best match on record.")

while True:
    global Answer
    pickedName = difflib.get_close_matches(userEmpName, employeeNames, 1)

    print(pickedName)
    print employeeNames

    if len(pickedName)==0:
        break

    userNameOK = raw_input("Is this the name of the person you're looking for?\n\n Type 'Y' or 'N'.\n\n")

    if (userNameOK=='n' or userNameOK=='N'):
        employeeNames.remove(pickedName[0])

    else:
        Answer=pickedName[0]
        break

print Answer+" is the right choice"

However using a global variable is generally bad practice so you can make a function to do all this thing and return the correct Answer

Also as employeeNames is modified every time a Name is removed from it should be better to create a copy of the list and work on that particular list

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top