Python - 我无法从列表中获取第一个之后的名称

标签 python

我是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/

相关文章:

python - 减少数据框行和查找

python - 为什么 exec ("break") 不在 while 循环中工作

Python层无法读取caffe框架中的hdf5文件

python - PyGObject 上的关闭系统托盘图标

python - 使用受 SSL 保护的 Redis 配置 Django channel

python - 检查 ansible 上 Jinja2 模板中的字典中是否存在 key

python - 在 Python 中序列化 float 安全吗?

python - 如何编写斐波那契数列?

python - 需要帮助写入 CSV 文件 Python 3.5

python - SQLAlchemy 创建标量子查询列并与外部子查询表中的列进行比较