为什么Python不能识别列表元素等于输入字符串?

这有点尴尬,但我是新手,还在使用Python3.2。
以下是问题代码:

选择 | 换行 | 行号
  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.  

问题是Found永远不会设置为True。例如,如果我输入"jack",则在第二次循环中,它为名称[Current]打印"Jack",为TestName打印"Jack",但条件
如果名称[当前]==测试名称
保持为假,程序继续循环。
我是要上厕所了,还是系统出了问题,还是...?其他测试显示将从以下代码片段返回True:

选择 | 换行 | 行号
  1. str1 = "Fred"
  2. str2 = "Fred"
  3. print(str1 == str2)
  4.  

嗯,当然!那么字符串比较没有问题吗?
你能帮忙吗?

# 回答1


它对我来说很好。请注意,名称的第一个字母是大写的,因此输入也必须大写。你可能会想试一试"

选择 | 换行 | 行号
  1.     if Names[Current].lower() == TestName.lower(): 

此外,python还拥有
风格惯例
,它规定变量名称应全部小写并带下划线(TestName-->test_name)。这有助于其他人阅读您的代码,因为您可以很容易地看出TestName是一个类,而test_name是一个变量。最后,您可以使用Python的"in"运算符:

选择 | 换行 | 行号
  1. if TestName in Names: 

标签: python

添加新评论