[Python] What explains pattern matching in Python not matching for 0.0, but matching for...

Discussão em 'Python' iniciado por Stack, Maio 10, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to understand how pattern matching works in Python. When I use matching with a type like float(), it matches 12.0, but when I use it with 0.0, it doesn't. I wonder why.

    I am new to pattern matching in Python, and I have been playing with it. I tried to match 12.0 with float values, as shown below.

    >>> t = 12.0
    >>> match t:
    ... case 13.0:
    ... print("13")
    ... case 12.0:
    ... print("12")
    ...
    12
    >>> t = 12.0
    >>> match t:
    ... case float():
    ... print("13")
    ... case 12.0:
    ... print("12")
    ...
    13
    >>> t = 12.0
    >>> match t:
    ... case 0.0:
    ... print("13")
    ... case 12.0:
    ... print("12")
    ...
    12
    >>> float()
    0.0
    >>> type(float())
    <class 'float'>
    >>> 13.0 == float()
    False
    >>>


    I am confused by the results. float() seems the same as 0.0 to me, so I would expect that if 12.0 matches float(), it would also match 0.0.

    I am happy it's not the case, as I want to match against types in some cases, but I would like to understand why this happens.

    Continue reading...

Compartilhe esta Página