字符串关系操作未按预期工作

时间:2018-02-05 18:07:34

标签: python string

def selectCatagory(catagoryVar):
catagoryResp = input("Do you want to select a catagory? Yes or no?: ")
while catagoryResp not in ['Yes','yes','No','no']:
    catagoryResp = input("Invalid input, please try again. TIP: Make sure there are no spaces: ")
if(catagoryResp in ['Yes,yes']):
    catagorySelResp = int(input("1.Food\n2.Astronomy\n3.Animal\nSelect from the following catagories (Select number): "))
    while catagorySelResp not in [1,2,3]:
        catagorySelResp = int(input("1.Food\n2.Astronomy\n3.Animal\nInvalid input,select from the following catagories (Select number): "))
    if catagorySelResp == 1:
        catagoryVar = FoodArray
    elif catagorySelResp == 2:
        catagoryVar = AstronomyArray
    else:
        catagoryVar = AnimalArray
else:
    print("Not working properly")

return catagoryVar

在这里,我想从用户那里获取一个输入,并根据该输入返回所选类别的数组。但是,无论我选择什么选项,它总是返回一个空数组,打印"不能正常工作"。即使我选择是,也会发生这种情况。但是,如果我给出无效输入,则while循环运行(这意味着输入正常工作)。我以前遇到过同样的问题,但无法找到解决问题的方法。为什么在if语句中没有正确比较字符串?我也尝试过if(catagoryResp ==" Yes"或catagoryResp ==" yes")但这也不起作用 提前致谢

1 个答案:

答案 0 :(得分:1)

if语句中的条件是一个包含逗号的单个字符串的列表:

if(catagoryResp in ['Yes,yes']):

它应该是两个单独的字符串:

if catagoryResp in ['Yes', 'yes']:

注意,条件在Python中不需要括号。