[Python] Python does not throw IndexError when evaluating if condition with 'and' operator...

Discussão em 'Python' iniciado por Stack, Dezembro 8, 2024.

  1. Stack

    Stack Membro Participativo

    I am currently helping a friend with getting into python and I came across this snippet of code, where I was unable to understand what was happening.

    def lbd_red(s):
    try:
    for i in range(len(s)):
    if s.isalpha() and s[i+1].isdigit():
    if s.isdigit() and s[i+1].isdigit():
    print("smth")

    return True
    except IndexError:
    return False


    I would expect this function to always return False, as the if statement essentially does nothing for the control flow, but should always throw an IndexError when evaluating s[i+1]. Yet somehow this is not what is happening. Here are a few examples of function returns:

    >> lbd_red("hu3")
    True
    >> lbd_red("hu3e")
    False
    >> lbd_red("hue3")
    True
    >> lbd_red("hue34")
    True
    >> lbd_red("hue34e")
    False
    >> lbd_red("hue33")
    True
    >> lbd_red("hue3e")
    False


    I have also tried debugging this code and when I watch s[i+1], I can see the IndexError ocurring, but it just does not seem to be thrown in the actual code.

    I am currently using Python 3.10.0, but I have also tried it on Python 3.12.

    PS: Yes, I know that the print statement will never be reached, but this is just some random code, its usefulness is not relevant to the question.

    Continue reading...

Compartilhe esta Página