By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,713 Members | 764 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,713 IT Pros & Developers. It's quick & easy.

Why doesn't Python recognize list element equal to input string?

P: 99
This is a bit embarrassing, but I'm new to Python, and using Python 3.2.

This is the problem code:

Expand|Select|Wrap|Line Numbers
  1. #a list of names
  2. Names = ["", "", "", "", ""]
  3. #initialised thus ...
  4. Names[1] = "Fred"
  5. Names[2] = "Jack"
  6. Names[3] = "Peter"
  7. Names[4] = "Kate"
  8.  
  9. Max = 4
  10. Current = 1
  11. Found = False
  12.  
  13. #get the name of a player from user
  14. TestName = input("Who are you looking for?")
  15.  
  16. while (Found == False) and (Current <= Max):
  17.         #next two lines put in in attempt to debug
  18.     print(Names[Current])
  19.     print(TestName)
  20.     print(Names[Current] == TestName)
  21.     if Names[Current] == TestName:
  22.         Found = True        
  23.     else:
  24.         Current += 1
  25. if Found == True:
  26.     print("Yes, they are on my list")
  27. else:
  28.     print("No, they are not there")
  29.  
  30. #stop the wretched console disappearing
  31. Wait = input("Press any key")
  32.  
The problem is that Found never gets set to true. If I enter "Jack" for example, on the second time round the loop it prints "Jack" for Names[Current] and "Jack" for TestName, but the condition
if Names[Current] == TestName
stays False, and program goes on looping.

Am I going potty, or is this a bug in the system, or ...? Other tests show True will be returned from the following snippet:

Expand|Select|Wrap|Line Numbers
  1. str1 = "Fred"
  2. str2 = "Fred"
  3. print(str1 == str2)
  4.  
Well, of course! So no problem with string comparison?

Can you help
Jun 9 '11 #1
Share this Question
Share on Google+
1 Reply


Expert 100+
P: 621
It works fine for me. Note that the first letter of the name is capitalized and so the input must also be capitalized. You might want to try"
Expand|Select|Wrap|Line Numbers
  1.     if Names[Current].lower() == TestName.lower(): 
Also, python has style conventions, which state that variable names should be all lower case with underlines (TestName --> test_name)". This helps someone else read your code as you can easily tell that TestName is a class and test_name is a variable. Finally, you can use Python's "in" operator:
Expand|Select|Wrap|Line Numbers
  1. if TestName in Names: 
Jun 9 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.