availableNums=["one","two","three","four","five"]
selectedNumbers=[]
for value in range(0,3):
selectedNumbers.append(raw_input("Choose a number:"))
if selectedNumbers not in availableNums:
print("The number "+str(selectedNumbers)+" isn't available/nBut it will be changed to six")
When I run this code and it asks for the numbers, I type in the numbers that are available in the list, but it still says that "The number ['one','two','three'] isn't available But it will be changed to six". Why is it doing that?
I think that I have to change the not
or in
part but I am not sure.
in
checks membership: a in b
is true if and only if a
is a member contained by b
.
Since availableNums
is a tuple of ints, selectedNumbers
, which is a list, isn't a member. You seem to be wanting to check whether selectedNumbers
is a subset of availableNums
.
You can either check each item in a loop:
for s in selectedNumbers:
if s not in availableNums
....
Or you can convert them to sets, if you're okay with checking all at once and failing completely if any of the selected numbers are invalid:
if not set(selectedNumbers) < set(availableNums):
....
Note that <
here, applied to sets, is the subset operator.
Also, as noted in a comment, raw_input
returns a string, but you're attempting to treat it as an integer. You can use int()
to parse the input string.
selectedNumbers
is a list. You are checking if the whole list is in availableNums
, not if each number in selectedNumbers
is in availableNums
.
It sounds like you want something like:
for selectedNumber in selectedNumbers:
if selectedNumber not in availableNums:
# selectedNumber from selectedNumbers is not in availableNums
Edit: As hatshepsut pointed out, your code places strings in selectedNumbers
, not integers. Use input
instead of raw_input
1 or convert to int
.
1 For Python 2. For Python 3, see What's the difference between raw_input() and input() in python3.x?
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.