我是Python新手,我的代码有问题..所以我想做的是询问一些随机名称,该程序应该告诉你名称是否在列表中
names = ["Demi", "Siru", "Datte", "Sony", "Jami", "Windy", "Paavo", "Roosa"]
x = input('Give a name: ')
for y in names:
if(x==y):
print( x + " is in a list" )
break
elif(y!=x):
print("it's not in a list")
break
最佳答案
正确的代码将遍历列表中的所有项目,如果有一个匹配项会跳出列表,但前提是没有一个匹配项,则得出结论:未找到它(以便该部分跳出循环),像这样:
for y in names:
if x == y:
print("{} is in the list".format(x))
break
else:
print("it's not in the list")
当然,完全不用循环也可以实现:
if x in names:
print("{} is in the list".format(x))
else:
print("it's not in the list")
关于Python - 我无法从列表中获取第一个之后的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52131774/