ThePythonGameBook

learn Python. Create Games

User Tools

Site Tools


en:python:goblins:step006

006 while loop

step006

while loop and conditionals

If you play the Goblin Dice Duel long enough you will maybe see Grunty going down before Stinky, but more likely you will find another odd behavior: both goblins knocked out ( below 0 hitpoints ) and still smashing each other with clubs ( undead goblins ?).

In fact, most games will not last 22 rounds. You can even not say in advance, at the time of writing the code how long a game will last at runtime.

the while loop

Lucky for you, there exist another loop structure in python that handles such insecureness: the while loop.

The official python documentation is as useless as those for the for loop for beginners:

while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]

so let me explain instead:

The while loop is used when you do not know in how many times to loop, but when you know when to stop looping. You can give such an condition or expression at the start of the loop as well as inside the loop.

expression

What is an boolean expression ? It's a kind of question that the python interpreter can answer with True or False.

Try out some examples in the python shell:

>>>1 == 1
True
>>>6 == 7
False
>>>"me" == "stupid"
False
>>>"me" != "stupid"
True
>>>9>8
True
>>>9>=8
True
>>>9<8
False
>>>"A"<"B"
True
>>>"c" in "abcdefg"
True
>>>hitpoints = 5
>>>hitpoints > 0
True
>>>1+1==2
True
>>>True
True
>>>False
False
>>>True == 1
True
>>>False == 0
True
>>>True < False
False

As you can see in an expression you usually compare two values or variables with one compare operator. See the python documenation on comparsions for more information.

condition at start of while loop

Now with the knoledge of expressions you can construct a while loop. The while loop will loop as long as the expression remains True. If the expression is never True the while loop will not even start. Be careful:

The expression will only be checked at the beginning of each loop, not inside the loop ( when computing the indented commands below the line with the colon ). If you need to make such checks in the middle of each loop, you need an if statement to break out of the loop.

if statement

What is an if statement ? It is a logical structure that you can find in nearly every programming language, also called an conditional. It will only computer certain commands if an condition is met ( an expression is True ) and will otherwise do nothing or compute commands below an else statement.

Let's take an look at the offical python documentation:

if_stmt ::=  "if" expression ":" suite
             ( "elif" expression ":" suite )*
             ["else" ":" suite]

Actually, this documentation is quite useful.

It means that for an if “block” you need at least an if statement, an expression and a colon <key>:</key>. Below the colon can stand several indented commands ( here called suite ). This suite will only be computed if the expression is True.

You can optional add an else command followed by an colon and some indented lines ( also “suite” in the documentation ). This suite will only be computed if the condition behind the if statement is False.

To make it complicated, you can chain if-else blocks to gether by adding one or more elif statements between the if and the else.

You best try out this example inside the python shell:

>>>a = 5
>>>b = 22
>>>if a > b:
...    print("a is bigger")
...
>>># nothing happended, because a was NOT bigger than b.
...
>>>if a > b:
...    print("a is bigger")
...else:
...    print("a is NOT bigger")
...
a is NOT bigger
>>>
>>>if a>b:
...    print("a is bigger")
...elif a<b:
...    print("a is smaller")
...else:
...    print("both are equal")
...
a is smaller
>>>

Try changing the values of a and b and run the if commands again. ( Remember the trick with the <key>↑</key> ).

breaking out

Now that you know how an if statement works, all you need is a command to escape out of the current while loop. This command is called break. If the python interpreter runs into an break command, the next line after the current while loop ( or for loop ) will be computed. The next non-indented line so to speak.

improved goblin dice duel

Type this in your python editor and let it run:

source code

click reload on your browser if you see no source code here or visit Github.com

code discussion

You noticed that i changed the random.randint() command from (1,6) to (0,6) ? It can now happen that one goblins roll a 0 die, aka completely miss his opponent. If that happens oft enough for both players, a game can now have many rounds. Thanks to the while loop instead of the for loop, this is no problem. Also no more undead goblins thanks to the while loop.

Because the while loop provides no loop variable ( unlike the for loop ), you must now take care of increasing the combatround variable yourself. This is done inside the while loop with this line:

combatround += 1

online code example

Click on the graphic to try the example out online:
Click me

step006
/var/www/horst/thepythongamebook.com/data/pages/en/python/goblins/step006.txt · Last modified: 2014/01/09 11:07 (external edit)