从用户那里获取输入并遍历列表以检查输入是否存在于列表中
Getting an input from the user and traverse over a list to chek if the input is present on the list
我有两个列表,我希望用户输入一个词,我的程序应该从我的列表中检查该词是否存在并打印一些东西,如果输入的词不在任何一个列表中,它必须执行else 语句。
这是我的代码:
animal = ['dog','goat','cow', 'ship']
city = ['JHB', 'CP', 'NY']
user = input('> ')
inp = user.split()
for word in inp:
if word == animal:
print(f"Your entry is: {word}")
elif word == city:
print(f"Your entry os: {word}")
else:
print("Invalid input")
当我 运行 代码跳转到“else”语句时。
而不是 ==
,使用 in
因为它是一个列表:
for word in inp:
if word in animal:
print(f"Your entry is: {word}")
elif word in city:
print(f"Your entry os: {word}")
else:
print("Invalid input")
我有两个列表,我希望用户输入一个词,我的程序应该从我的列表中检查该词是否存在并打印一些东西,如果输入的词不在任何一个列表中,它必须执行else 语句。
这是我的代码:
animal = ['dog','goat','cow', 'ship']
city = ['JHB', 'CP', 'NY']
user = input('> ')
inp = user.split()
for word in inp:
if word == animal:
print(f"Your entry is: {word}")
elif word == city:
print(f"Your entry os: {word}")
else:
print("Invalid input")
当我 运行 代码跳转到“else”语句时。
而不是 ==
,使用 in
因为它是一个列表:
for word in inp:
if word in animal:
print(f"Your entry is: {word}")
elif word in city:
print(f"Your entry os: {word}")
else:
print("Invalid input")