For Loops

neurons, brain cells, brain structure

So far in our guess the number game, the user only gets one guess. In this tutorial, we will show you how to allow the player to get more guesses using for loops

In a for loop, a given command is repeated the desired amount of times. The code for this is:

For i in range(min_num, max_num):

The subsequent lines must be indented with the TAB key. Below is an example of the function at work. Watch the output change with each iteration. We wont use this functionality in this tutorial but we may in future tutorials.

Breaking from loops

What if we want to exit the loop early? Maybe you want to exit the loop when a certain condition is fulfilled. We can do this using:

break

This stops the loop immediately. Next we will see this in practice.

Try it yourself

We are now ready to add the for loop into python. After adding the code you should see something similar to the code below. Try changing the number of guesses you have to make the game easier or harder. Challenge: create a variable to num_guesses for the number of total guesses.

Conclusion

Now we can use for loops to set the number of guesses the player has. Next lesson we will learn more about the if() function and make our game strategic as opposed to just guessing.

3 thoughts on “For Loops

Leave a Reply

Your email address will not be published. Required fields are marked *