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

## Lesson Video 18

• 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 definite count loops in a computer program.

## Key Terms

While loop Repeat Until loop Iteration Iterator Counter Repeat Condition Infinite loop

## Iteration Using definite count loops

There are two major types of loops in Python, for loops and while loops. If you want to repeat a certain number of times (definite count), you will normally use a for loop.

For example, a for loop can be used to print all student records since the computer knows exactly how many students there are.

### For Loop Syntax

```
for variable in range(number):
indented code goes here...

```

## Using the range function

For loops will iterate through a sequence of numbers using the "range" function. The range function allows you to specify up to three values

range(start value, stop value, step value)

• The 'start value' is the value the for loop will start at (default value is 0)
• The 'stop value' is the value the for loop will stop at ( it will never include the stop value so if 5 is used it will stop when it gets to 5 )
• The 'stop value' is the only value that must always be delcared
• The 'step value' is the size of the increments for each loop, for example if the step value was 2 then the loop variable(iterator) would increase in value each time by 2 - (default value is 1)

Below is an example of a for loop using the range function with just the stop value set to 5 so it will repeat the code inside the loop 5 times

### Printing a range of numbers

You can use the range function in a for loop to print out numbers within a range you decide by setting both the start value and the stop value.

For example:

• If we wanted our loop to sequence through the values 3 to 7 one at a time we would make our start value = 3 and our stop value = 8
• Why 8 and not 7? Well because our range will stop when it gets to the stop value

Python example:

Use the code window below

1. See if you can print out the range of numbers from 2 to 10.

2. Now ask the the user to enter two numbers and print out the range between those two numbers

### The final parameter in our range function allows us to choose the size of the increment in our loop

For example if we set the step value = 2

• our loop would increase by 2 each time see examplke below
• print out all of the odd numbers from 1 to that number