SotK's Python Tutorials - Part 3: While Loops

Started by Son of the King, June 28, 2011, 11:18:47 PM

Previous topic - Next topic

Son of the King

SotK's Python Tutorials
Part 3: While Loops




Loops:

The end of the last section mentioned loops and iterable data structures. An iterable data structure is simply a data structure made up of elements that can be looped through, imagine a list of things for example. A loop would allow you to look at each item in a list, which is useful in many areas of programming. Also loops allow the same action to be performed many times with only a small amount of code, or even an indefinite amount of times which means that programs for entering data and the like can be simplified greatly/are even possible.

In Python, a simple while loop looks like this:

Code (Python Loop) Select
while <condition>:
    ...
    ...
...


A while loop performs the code in the loop (in Python this is the code indented below the line with the loop condition in) while a specified condition is true. This condition can be anything that gives a boolean result (or a result that can be interpreted as a boolean). You should be careful when using loops that your condition evaluated to false when you need the loop to stop, or you will have an infinite loop. A simple example of an infinite loop could be:

Code (Infinite Loop) Select
while True:
    print('This is an infinite loop')
...


Since the condition of this loop is always true, the loop will never stop and This is an infinite loop would be printed to the command line infinitely, or until you force the program to terminate or your computer gives up.

One way to fix this is to use a variable to count the number of times the loop has performed the code inside it, and to make it stop after a certain number.

Code (Loop with counter) Select
count = 0
while count <= 9:
    print('This code is performed 10 times')
    count += 1
...
...


This will print This code is performed 10 times onto the command line 10 times before stopping. The integer count has 1 added to its value at the end of each iteration, so that after 10 times count = 10, meaning the condition count <= 9 is false and the loop finishes. This means you can now create a loop of any length you need. But what happens if you don't know how many iterations you need?

If you are making a game loop (more on this concept if I ever write part of this about game programming), then you will not know how many times it should run. The game loop generally draws each frame, and handles any events that occur (such as user interaction) during the frame. Since we don't know how many times we will need to go through this loop, we need it to be similar to the infinite loop above but with the ability to get out of it if needs be. This can be done in two ways. Firstly, you can use a boolean variable to decide when to stop the loop like so:

Code (With Boolean Variable) Select
running = True
while running:
    ...
    if game closed:
        running = False


This way, the loop runs until the game is closed, when we set running to False. This means that the condition for the loop to keep running is False, and so it stops.

Alternatively, we can use the break statement to exit a loop at a chosen point. This works as follows:

Code (With Break Statement) Select
while True:
    ...
    if game closed:
        break


This will force the program to exit the loop at the point where the break statement is. Note in these two examples, "game closed" cannot be a real variable name, it is just there as an example of when it would be useful to want to exit an infinite loop. That's about everything I can think of about basic while loops for now. Next time we will see a for loop for the first time, and then more complex data structures such as lists.

<-- Part 2: Variables, Data Types, Conditional Statements
--> Part 4: Lists, More Strings and For Loops


Othko97

What's next? I'd suggest if, for and other flow control functions.
I am Othko, He who fell from the highest of places, Lord of That Bit Between High Places and Low Places Through Which One Falls In Transit Between them!


Jubal

I should get round to learning Python properly, I used it a bit for M&B modding but that was really just input files.
The duke, the wanderer, the philosopher, the mariner, the warrior, the strategist, the storyteller, the wizard, the wayfarer...

Son of the King

You should do!

Othko, if is already covered in the part 2 ;) . Next will be lists and more detail on strings (effectively a list), which lead nicely into for loops.