0
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?

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
  • The second part of the if statement is list_1 which return true as long as the list is not None or empty, therefore you will always return True – Yossi Levi Sep 17 '20 at 14:46
  • 1
    Does this answer your question? [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Wups Sep 17 '20 at 14:47
  • 1
    Some tips: 1. Don't use `list` as a variable name -- it's a builtin function. 2. Why use a list comprehension to make a list from a list? `range()` returns a list, no need to transform it. 3. No need to use `if boolean: return True else: return False` logic. Just use `return boolean` – Fred Larson Sep 17 '20 at 14:49
  • Actually, I wasn't correct that `range()` returns a `list` (though that was true before Python 3). But it does return an iterable, and that's all that's needed here. If you really did need a list you could say `list(range(...))` (assuming you didn't redefine `list`). – Fred Larson Sep 17 '20 at 14:56

3 Answers3

2

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)

SWater
  • 384
  • 1
  • 13
2

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.

Tsubasa
  • 1,389
  • 11
  • 21
0

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.

George Bou
  • 568
  • 1
  • 8
  • 17