Reputation: 65
def almost_there(n):
list=[x for x in range(90,111)]
list_1=[i for i in range(190,211)]
if n in list or list_1:
return True
else:
return False
print(almost_there(1))
>>> True
Why is it giving true even when the value is 1?
Upvotes: 0
Views: 70
Reputation: 1429
Try this one.
def almost_there(n):
list_1 = [x for x in range(90,111)]
list_2 = [i for i in range(190,211)]
if n in list_1 or n in list_2:
return True
else:
return False
print(almost_there(1))
# False
Check if n is either in list_1
or list_2
. If you do if n in list_1 or list_2
this will only check if n
is in list_1
and not list_2
.
One more thing don't use list
as your variable name. That will override the list()
function.
Upvotes: 2
Reputation: 588
The problem is in you if
statement.
if n in list or list_1:
evaluates to: 1) if n in list
(false) or
2) if list_1
(true)
Now the second argument is always going to be True
because it's a populated list.
The correct way to write your if
statement should be: if (n in list or n in list_1)
This evaluates to if
1) n in list
(false) or
2) n in list_1
(false)
And thus you 'll get the expected results.
Upvotes: 0
Reputation: 443
Because of the condition:
if n in list or list_1:
When you have or condition, both part of the condition should be False
for the condition to be False
In your case:
n is not in list
is False , but list_1
is not empty and is True.
So you have
if False or True:
-- and this returns True (the condition is fulfilled)
Upvotes: 2