【问题标题】:how to do if and else statements in python lists如何在 python 列表中执行 if 和 else 语句
【发布时间】:2017-09-27 15:57:49
【问题描述】:
user = input("userinput: ")

myList = ["Noah", "Mike"]
for item in list:
    if user == item:
        print("hello {}".format(user))
    else:
        print("invalid")

我想要做的是,如果你在列表中说了什么你get hello (and the name you pick)

例如:

input: Noah

output: hello Noah

如果你没有正确地将任何东西放在列表中

input: Mikee

output: invalid

所以基本上我在 python 列表中询问更复杂的 if 和 else 语句

【问题讨论】:

标签: python python-3.x list


【解决方案1】:

您正在遍历列表中的每个项目并打印其有效性。您只想检查一次:

user = input("userinput: ")

myList = ["Noah", "Mike"]
if user in myList:
    print("hello {}".format(user))
else:
    print("invalid")

【讨论】:

    【解决方案2】:
    user = input("userinput: ")
    
    myList = ["Noah", "Mike"]
    
    if user in myList:
        print("hello {}".format(user))
    else:
        print("invalid")
    

    您只需检查列表中是否存在值。

    【讨论】:

      【解决方案3】:

      似乎是三元运算符的一个很好的用例:

      user = input("userinput: ")
      myList = ["Noah", "Mike"]
      
      print("hello {}".format(user)) if (user in myList) else print("invalid")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多