samedi 4 juillet 2020

Python: When to use while vs if/else

I am a beginner and I am beginning to learn about 'while' statement loops to perform iteration. However, earlier on I have learnt about 'if/else' statements and how one can perform recursion using if/else by returning a variable as well. Here's a simple countdown function using while statement:

def countdown(n):
    while n > 0:
        print(n)
        n = n-1
    print('Blast off!')

And for comparison, here is a simple countdown function using if/else and recursion.

def countdown(n):
    if n > 0:
        print(n)
        return countdown(n-1)
    elif n < 0:
        return None
    else:
        print('Blast off!')
        return

As you can see, the two functions do almost exactly the same thing, with the only difference being that the if/else statement accounts for a case where n < 0 and returns a None value, while the 'while' statement simply omits the loop and prints 'Blast off!' even if n < 0 anyway. (If there is a way to factor this in the while statement, I would love to learn, do suggest!)

My question is, seeing how the same thing can be done in if/else statements and while statements and vice versa, I would like to know a case where they are clearly differentiated and one is clearly preferable to the other. Is there a subtle conceptual difference between the two types of statements that I am missing, or are they interchangeable in usage?

Aucun commentaire:

Enregistrer un commentaire