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)
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
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.