OR behaviour in python:

后端 未结 3 1954
离开以前
离开以前 2020-11-30 14:26

I have written the following piece of code, all i want to do is print a yes for if the number passed is a string representation of 1, 0 or 2 and for everything else a false:

3条回答
  •  渐次进展
    2020-11-30 15:20

    Because every expression between an or is evaluated as a boolean expression.

    if True evaluates to True, if 1: evaluates to True, if "0": evaluates to True.

    So what you wrote is more or less the equivalent to:

    if number is "1":
        print "Yes"
    elif "0":
        print "Yes"
    elif "2":
        print "Yes"
    else:
         print "no"
    

    You should have written if number is "1" or number is "0" or number "2": or, more pythonic: if number in ("1", "0", "2"):

提交回复
热议问题