determine if an number is in a list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: determine if an number is in a list (/thread-13887.html) |
determine if an number is in a list - Dbeah - Nov-05-2018 what should i use for the elif statement to get number not in the list import random def rollBall(): system = [0,9,20,24,25,35] spin = random.randint(0,36) if spin in system: return True elif spin ??? system: return False RE: determine if an number is in a list - buran - Nov-05-2018 import random def rollBall(): system = [0,9,20,24,25,35] spin = random.randint(0,36) return spin in system RE: determine if an number is in a list - stullis - Nov-05-2018 You really don't need the elif. You could use a else instead because the initial logic statement is binary: the number either is or is not in the list. Since there are no other possibilities, you only require the one test at the beginning. If that test fails, then the number is evidently not in the list. With that out of the way, you could use @buran's answer or you could use the keyword "not": import random def rollBall(): system = [0,9,20,24,25,35] spin = random.randint(0,36) if spin in system: return True elif spin not in system: return False RE: determine if an number is in a list - woooee - Nov-06-2018 No elif is necessary, as you return True if found and code exits there import random def rollBall(): system = [0,9,20,24,25,35] spin = random.randint(0,36) if spin in system: return True ## if no return above then num not in system return False RE: determine if an number is in a list - wavic - Nov-06-2018 The return False is useless because the function returns None if the if condition isn't met. None evaluates to False.
RE: determine if an number is in a list - buran - Nov-06-2018 (Nov-06-2018, 04:06 AM)wavic Wrote: The return False is useless because the function returns None if the if condition isn't met. None evaluates to False.Although it's true that None is evaluated to False your suggestion has at least 2 weak points - (i) you don't know how the value returned from function is used later on in the code and there might be undesired side-effects when return None instead of False; and (ii) Explicit is better than implicit. I would always prefer my original suggestion, but for completeness, one more possible code snippet is if spin in system: return True else: return Falsei.e. there is no need for second evaluation. RE: determine if an number is in a list - Gribouillis - Nov-06-2018 You can also use return bool(spin in system)This makes it explicit that the return value is True or False , although this is probably already the case with the in operator.
RE: determine if an number is in a list - buran - Nov-06-2018 (Nov-06-2018, 08:51 AM)Gribouillis Wrote: You can also usespin in system is already a bool, no need to cast it |