Loops
There are 2 types of loops that you have already learnt about - COUNT-CONTROLLED and CONDITION-CONTROLLED.
In this lesson we will use both to improve on the simple dice game.
In this lesson we will use both to improve on the simple dice game.
COUNT-CONTROLLED LOOP KNOWN IN PYTHON AS A FOR LOOP
A for loop repeats the code indented inside it a set number of times. This number can be fixed by the programmer or it can be taken in as an input.
Below you can see the standard SYNTAX for a for loop in Python.
What do you think we display on screen when the code is run?
Copy out the code and test your prediction.
Below you can see the standard SYNTAX for a for loop in Python.
What do you think we display on screen when the code is run?
Copy out the code and test your prediction.
Now add this code
Debugging task
- Open a new Thonny file and save it as 'for loop'.
- Copy out the code above and run it.
- Fix any syntax errors.
- Add a comment to your code to explain what happens in a for loop.
- Use the debugger to STEP INTO (F7) the code to see exactly how it works and how the variable i works.
Adding a for loop to the dice game
- Make a copy of your extended dice game.
- Using the copy of the game, make changes as shown in the code below
Notice that you have added the time library as well as the random library.
You have also used input to ask a question.
Continue adding to the count-controlled dice game
Complete the code by indenting the if...elif...else selection block
EXTENSION FOR LOOP TASKS :
|
CONDITION-CONTROLLED LOOP KNOWN IN PYTHON AS A WHILE LOOP
In a new Thonny file saved as 'while loops', copy out the example shown below including the comments.
Example 2
|
Adding a while loop to the simple dice game
- Make another copy of your simple dice game. Call this "dice game with while".
- Using your new knowledge of while loops, add a variable and a while loop to control the game.
EXTENSION WHILE LOOP TASKS :
|