【问题标题】:Checking if a variable is existent within a list检查列表中是否存在变量
【发布时间】:2016-09-09 17:15:35
【问题描述】:

我目前正在使用代码

names = ["Bob", "Joe", "Jack"]
name = raw_input("Please enter your name.")
print ("Hello", name)

我想创建一个 if 语句来检查输入的名称是否在名称列表中。我假设有一些命令可以检查这个,我在这里搜索文档或问题时找不到它。现在,代码创建了一个名称列表,一个存储输入名称的变量,并打印“Hello name”。我可以创建 if 语句;我只想知道那个命令/方法是什么。

谢谢!

【问题讨论】:

    标签: python list input global-variables


    【解决方案1】:

    使用in 运算符。

    if name in names:
        print ('The entered name is in the list of names.')
    else:
        print ('The entered name is not in the list of names.')
    

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 2018-04-27
      • 2014-09-08
      • 2017-02-13
      • 2011-12-19
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多