469,336 Members | 6,108 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,336 developers. It's quick & easy.

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

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"
  9. Max = 4
  10. Current = 1
  11. Found = False
  13. #get the name of a player from user
  14. TestName = input("Who are you looking for?")
  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")
  30. #stop the wretched console disappearing
  31. Wait = input("Press any key")
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)
Well, of course! So no problem with string comparison?

Can you help
Jun 9 '11 #1
1 3012
626 Expert 512MB
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.

Similar topics

10 posts views Thread by Terry Carroll | last post: by
2 posts views Thread by hogcia | last post: by
5 posts views Thread by antar2 | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Marylou17 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.