Python Forum

Full Version: determine if an number is in a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
import random
 
def rollBall():
    system = [0,9,20,24,25,35]
    spin = random.randint(0,36)
    return spin in system
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
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 
The return False is useless because the function returns None if the if condition isn't met. None evaluates to False.
(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 False
i.e. there is no need for second evaluation.
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.
(Nov-06-2018, 08:51 AM)Gribouillis Wrote: [ -> ]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.
spin in system is already a bool, no need to cast it