Including two things it will check for in one if statement in python
lets say I have a program that runs like this in python
x=raw_input("Please enter name: ")
if x=="David" and "Jonathon"
p开发者_JAVA百科rint "Whatever"
how do I get two things such as Jonathon and David so it excepts both of these scenarios and for both executes print "Whatever". I know that ["David" and "Jonathon"] isn't the proper syntax for this so I want to know what is. I also know how to do this be adding an elif statement but I want to know another way.
You can do:
x=raw_input("Please enter name: ")
if x=="David" or x=="Jonathon":
print "Whatever"
Or you can do:
names=["Bob","Joe"]
x=raw_input("What is your name?\n")
if x in names:
print "Whatever"
If you are dealing with large data.
names = ["David", "Jonathon"]
x=raw_input("Please enter name: ")
if x in names:
print "Whatever"
You're looking for logical OR. What you're trying to do here as far as I understand is say if x=="David" OR x=="Jonathon" then do something so you want the following.
Clearly x cannot have two values so AND will never evaluate to true. This would be the correct code (or velociraptors version using an array)
x=raw_input("Please enter name: ")
if x=="David" or x=="Jonathon":
print "Whatever"
Given the discussion, here's the whole hog using a simple config file (I've tested the conf.read().split() so please, no comments about it). The config file would contain one name per line with no spaces (so no "firstname surname"):
conf = open('/path/to/config.txt','r')
names = conf.read().split()
x=raw_input("Please enter name: ")
if x in names:
print "Whatever"
If your list of names had the potential to get very long, this would be the most maintainable solution.
精彩评论