Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Loop Details
#1
Often in computer programming you want to do the same thing over and over again. You may want to do it a certain number of times, or for certain items, or until something specific happens. But sooner or later, you will want to do something over and over again. Programmers call this 'looping' (or 'iteration' when they're being fancy), and the code that does it is called a 'loop'. This tutorial is about loops, but I will try no to get too loopy while doing it.

Python implements two loop statements: for and while. Other languages often implement other loop statements, such as until or for each. Python goes for simple syntax, but for and while can handle all of the loop types commonly used in other languages. We'll start with the while loop, which looks like this:

n = 9
while n != 1:
    print(n)
    if n % 2:
        n = 3 * n + 1
    else:
        n = n // 2
print(n)
If you run this code, you will see that it prints out the Collatz Conjecture sequence for n = 9. How does it do that? Let's step through the code. First, we set n to 9. Then the while loop checks the expression n != 1. That returns True, since 9 is not 1. So the indented code under the while statement is executed. This indentation is very important. Often new Python programmers don't indent everything they want to be run each time through the loop. If it's not indented, it won't be run as part of the loop.

So the code prints n (9), and then checks to see if it is odd (if n % 2:). If n is odd, it is multiplied by three and then added to one. Otherwise it is divided by two. In the case of 9, n is odd, and n becomes 28. That's it for the indented code.

Up to this point the while loop has just acted like an if statement: it checked an expression, and if that expression was True, it runs the indented code. In fact, some newbies use while loops as if statements, which rarely works out well. This is because after the while loop finishes executing the indented code, it goes back to the while statement and checks the condition again. So now n is 28, which is still not 1, so the indented code executes again. This time n is even, so it is divided by 2, and you get 14. Fourteen is still not one, so the while loop keeps repeating this calculation through 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, and finally 1. Once n == 1, the while loop goes back and checks the conditional, which is finally False. The the while loop skips the indented block of code, and the final print statement is executed, printing 1.

If we had set n to 1 at the beginning, the condition would have been False on the first check, and the indented code would never have been executed. All that the program would have done is print '1'.

The condition in the while statement can be any condition you would see in an if statement. However, there is one condition you often see in while loops that I don't think I've ever seen in an if statement:

while True:
    food = input('What would you like for breakfast? ')
    if input.lower() == 'spam':
        break
print(f'Okay, {food} for breakfast.')
The key part here is the break statement. The break statement exits the loop and goes to the end of the indented code. It doesn't matter what the loop statement is, it stops executing the loop statement and moves on. This is handy for verifying input, like the above code does. If we had to use the condition in the while statement to end this loop, it would look like this:

food = input('What would you like for breakfast? ')
while food.lower() != 'spam':
    food = input('What would you like for breakfast? ')
print(f'Okay, {food} for breakfast.')
[python]

Now, you might think this is actually better. It is one line less of code. However, you now have a repeated line of code. That's generally a bad idea. The problem comes when you have to do any processing on the input before validating it. If you do, then you have to repeat all of that processing twice (once before the loop and once in the loop). So [inline]while True:[/inline] can be a useful construct. There can be a problem, however. Say we don't think things through correctly, and our while loop looks like this:

[python]
while True:
    food = input('What would you like for breakfast? ')
    if input.lower() == 'spam':
        print(f'Okay, {food} for breakfast.')
Notice that we left out the break statement. Now the loop never stops asking the question, even if you enter exactly the right answer. The condition is always True, so the indented code always executes. This is called an "infinite loop," and it is the bane of programmers in any language (although we used to have fun messing up the computer lab with them in middle school). It is for this reason that some programmers say you should never use while True:. I disagree with that. Let's go back to our Collatz loop, but let's say we want to try a variation on the Collatz Conjecture:

n = 9
while n != 1:
    print(n)
    if n % 2:
        n = 2 * n + 1
    else:
        n = n // 2
print(n)
The problem here is that 2n+1 is always odd. So if we start with an odd number, or divide to one, the code will go into an infinite loop making larger and larger odd numbers. Indeed, that will happen with any starting number except a power of two. So even a while loop with a real condition can become an infinite loop if we're not careful. So always be sure to check your while loops to make sure the condition can be met, or a break statement can be executed.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
Loop Details - by ichabod801 - Sep-13-2019, 06:41 PM
RE: Loop Details - by ichabod801 - Sep-13-2019, 06:42 PM
RE: Loop Details - by ichabod801 - Sep-13-2019, 06:43 PM
RE: Loop Details - by ichabod801 - Sep-13-2019, 06:44 PM
RE: Loop Details - by ichabod801 - Sep-13-2019, 06:47 PM
RE: Loop Details - by ichabod801 - Sep-13-2019, 06:49 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020