Computing
Computer Science LearnITWithMrC ⛯ Year 7 Year 8 Year 9 GCSE

## Lesson Video 17

• Watch the Lesson video
Make notes on your notes sheet.
Make notes on your notes sheet.
• Complete the learning activities
Make any notes on your notes sheet.
• Check the Learning outcomes

## What do I need to Learn?

 I need to learn how to understand and know how to use indefinite Pre-test loops in a computer program. I need to learn how to understand and know how to use indefinite Post-test loops in a computer program.

## Key Terms

For loop Iteration Repeat Condition Infinite loop

## Iteration with conditions - While Loops

A for loop is used when a program knows it needs to repeat a block of code for a certain number of times. A while loop is used when a program needs to loop until a particular condition occurs.

Oddly enough, a while loop can be used anywhere a for loop is used. It can be used to loop until an increment variable reaches a certain value. Why have a for loop if a while loop can do everything? The for loop is simpler to use and code. A for loop that looks like this:

```Using a for loop to print the numbers 0 to 9
for i in range(10):
print(i)
```

...can be done with a while loop that looks like this:

### Using Increment Operators

Increment operators are often used with while loops. It is possible to short-hand the code:

```i = i + 1
```

With the following:

```i += 1
```

In the while loop it would look like:

```i = 0
while i < 10:
print(i)
i += 1
```

This can be done with subtraction and multiplication as well. For example:

```i *= 2
```

Is the same as:

```i = i * 2
```

Run the code below and see if you can figure out what is being output:

### Fix the while loop

1. What is wrong with this loop that tries to count to 10? What happens when it is run? How should it be fixed?

### Looping Until User Wants To Quit

A very common operation is to loop until the user performs a request to quit:

```Looping until the user wants to quit"
quit = "n"
while quit == "n":
quit = input("Do you want to quit? ")
```

There may be several ways for a loop to quit. Using a Boolean variable to trigger the event is a way of handling that. Here's an example:

```
Looping until the game is over or the user wants to quit"

done = False
while not done:
quit = input("Do you want to quit? ")
if quit == "y":
done = True

attack = input("Does your elf attack the dragon? ")
if attack == "y":