OR behaviour in python:

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

    The problem is that your code, to Python, reads like this:

    if (number is "1") or "0" or "2":
    

    And as any non-empty string evaluates to True, it's always True.

    To do what you want to do, a nice syntax is:

    if number in {"1", "0", "2"}:
    

    Note my use of a set here - while it doesn't matter too much in this case (with only three values) checking against a set is faster than a list, as a membership test for a set is O(1) instead of O(n).

    This is simply a nicer and easier of writing this:

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

    Which is what you wanted.

    Note when making a comparison for value you should always use == not is - is is an identity check (the two values are the same object). Generally you should use is for stuff like is True or is None.

    If you wanted to handle this as a number, you could do something like this:

    try:
       value = int(number)
    except ValueError:
       value = None
    if value is not None and 0 <= value <= 2:
        ...
    

    Which could be more useful in situations where you want to compare to a large range of numbers. Note my use of Python's useful comparison chaining (0 <= value <= 2 rather than 0 <= value and value <= 2).

提交回复
热议问题