Search code examples
python-3.xif-statementdifflib

Why is this string comparison not working? (difflib)


This code should be printing "Adam" when the user asks a question like: "what's your name." Instead, the if statement never returns true. Please help!

import difflib
    while True:
     talk = input("Please say something > ")
     temp = (difflib.get_close_matches(talk, ['What is your name?', 'Hello', 'peach', 'puppy'],1,0.2))
     print(temp)
     if temp == "['What is your name?']":
      print("Adam")
      break
     continue
     
    input()

Apologies in advance if this is a stupid question.


Solution

  • Since temp is a list and you want to check if the first element of that list is What is your name? then you can't just do it all as a string as in put it like "['What is your name?']" as you have done, you need to check the first element (index 0) and then compare this:

    if temp[0] == "What is your name?":
        ...
    

    And this will work. Good luck!