简体   繁体   English

如何在python列表中执行if和else语句

[英]how to do if and else statements in python lists

user = input("userinput: ")

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

what I am trying to do is if you said something in the list you get hello (and the name you pick)我想要做的是,如果你在列表中说了些什么,你get hello (and the name you pick)

for ex:例如:

input: Noah

output: hello Noah

And if you do not put any thing in nothing in the list correctly如果你没有在列表中正确地放入任何东西

input: Mikee

output: invalid

so basically I am asking a more complex if and else statement in python lists所以基本上我在python列表中询问更复杂的if和else语句

You're iterating over each item in the list and printing its validity.您正在迭代列表中的每个项目并打印其有效性。 You want to check just once:您只想检查一次:

user = input("userinput: ")

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

myList = ["Noah", "Mike"]

if user in myList:
    print("hello {}".format(user))
else:
    print("invalid")

you need to just check that value is exist in list or not.您只需要检查列表中是否存在该值。

Seems like a great use case for ternary operator:似乎是三元运算符的一个很好的用例:

user = input("userinput: ")
myList = ["Noah", "Mike"]

print("hello {}".format(user)) if (user in myList) else print("invalid")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM