OR behaviour in python:

后端 未结 3 1957
离开以前
离开以前 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:08

    The correct syntax is as follows:

    if number == "1" or number == "0" or number == "2":
        print "Yes"
    

    Or the more Pythonic:

    if number in ["1", "2", "3"]:
        print "Yes"
    

    Or you can cast to int and try:

    if int(number) in range(1,4):
        print "Yes"
    

    The reason your code evaluates to True is all the time is because it is evaluating the truth of the "0" and "2", which as statements are true in Python.

提交回复
热议问题