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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • julietbrown
    New Member
    • Jan 2010
    • 99

    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:

    Code:
    #a list of names
    Names = ["", "", "", "", ""]
    #initialised thus ...
    Names[1] = "Fred"
    Names[2] = "Jack"
    Names[3] = "Peter"
    Names[4] = "Kate"
    
    Max = 4
    Current = 1
    Found = False
    
    #get the name of a player from user
    TestName = input("Who are you looking for?")
    
    while (Found == False) and (Current <= Max):
            #next two lines put in in attempt to debug
    	print(Names[Current])
    	print(TestName)
    	print(Names[Current] == TestName)
    	if Names[Current] == TestName:
    		Found = True		
    	else:
    		Current += 1
    if Found == True:
    	print("Yes, they are on my list")
    else:
    	print("No, they are not there")
    
    #stop the wretched console disappearing
    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:

    Code:
    str1 = "Fred"
    str2 = "Fred"
    print(str1 == str2)
    Well, of course! So no problem with string comparison?

    Can you help
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    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"
    Code:
        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:
    Code:
    if TestName in Names:

    Comment

    Working...