0
or function
if "2" or "4" or "6" or"5" or "8" in str(71): print("yes") >>yes Why does the code print yes? and in what way can I improve the code so that if any of the 5 numbers in the string it will return False
5 odpowiedzi
+ 8
Sorry i wrong. In the previous version, you checked only ('2' in str (71))
Need like this:
for i in [2, 4, 6, 5, 8]:
if str(i) in str(71):
print('yes')
break
+ 9
Your syntax is causing the problem.
if "a" or "b" in x
will always evaluate as True regardless of what x is
because you are evaluating
(if "a") or (if "b" in x)
Since "a" is not "", 0 or None, 'if "a"' evaluates as True so the rest of the "or" expression doesn't get evaluated.
What you want is
if "a" in x or "b" in x etc.
Here's a way using the any() function. Delete "not" if you want the opposite answer.
def num_in_string(lst, num):
"""Find whether number in list is in number string."""
return not any(c for c in lst if str(c) in str(num))
print(num_in_string([2, 4, 6, 7], 71))
+ 4
Because the first step is checking ('8' in str (71)), this returns False. When checking ('5' or False) returns '5' and this is already True
Try it like this:
if ("2" or "4" or "6" or "5" or "8") in str(71):
print("yes")
0
Thank you
0
can you explain a little why does it work this way?