Use of Else Statement with For loops in Python

So, its very interesting that we can use else statement with for loops or while loops in python. And an interesting and quite useful use of this is shown in the code below which I wrote for a problem statement of HackerRank Python section.

Another interesting inference you can make from this code is that, here I have stored functions in a list, which is dubious looking and also bit cryptic but it is very useful and  efficient, it also shows that the str methods can be used in two ways:

Like str.islower(some_string) or some_string.islower().

Below is the code which covered all the possible test cases.

if __name__ == '__main__':
    s = input()
    str_methods=[
        str.isalnum,
        str.isalpha,
        str.isdigit,
        str.islower,
        str.isupper,
    ]
    for method in str_methods:
        for char in s:
            if method(char):
                print("True")
                break
        else:
            print("False")

Comments

Popular Posts