top of page

Python - Iteration

For Loops

Editor

Execute

A for loop is a count controlled loop.

​

It repeats for a certain number of times as stated in the range brackets.

​

The first number (1) states the number to start on.

​

The second number is an exclusive end. This means it actually finishes on the number before. (11 will end on 10).

for loop.png

You need a colon at the end of the loop line.

​

Each line to be repeated must be indented (press the tab key).

​

You can use the loop number within the loop itself.

1. Write a for loop to print your name 8 times. (Count it to double-check it prints eight times.)

​

2. Use a for loop to print each number between 10 and 50.

​

3. Use a for loop from 1 to 10. Print the 3 times table by multiplying number by 3 underneath the loop.

​

4. Ask the user to input a whole number (call it num1). Write num1 in your range brackets to repeat any message that many times.


5. Ask the user to input a whole number (call it num1) and then input a word. Print the word by the number they entered. (Hint: Use num1 in the range.)

​

6. Delete your code and copy these 3 lines:

​

#Delete the space after the colon

for number in range(0,21,2):​
  print(number)

​

    What happens when you run this code?

​

7. Use Q6 to help you print 0 to 100, going up in 5s. Think about the 3 values you need in the range brackets.

​

8. Use Q6 to help you print 100 down to 0, backwards by 1. Think about the 3 values you need in the range brackets.

Tasks

While Loops

Editor

Execute

A while loop is a condition controlled loop.

​

While loops repeat as long as the condition is true. As soon as the condition becomes false, the loop will end.

1. Change the program in the editor to repeat the loop while a number is not equal to 33.

​

2. Make a new while loop that asks the user to enter a whole number. While the number is less than or equal to 1000, keep repeating.

​

3. Make a new while loop for while a colour is not equal to purple (or any colour you want). Ask the user to enter a colour inside of the loop. Don't forget to set colour to "" before you start.

​

4. Edit your colour program to count how many guesses were made. Make a new variable called count and set it to 0 at the start of the program. Increase it by 1 in the loop, using count = count + 1.


5. While a total is less than 100, ask the user to input a decimal number. When it is over 100, print ‘COMPUTER OVERLOAD’. You need a variable called total. Increase the total each time with total = total + number. Don't forget to start it at 0.

Tasks

!= means ‘not equal to’. The loop below will repeat as long as the password is not equal to “abc123”.


Any variable you use in your condition must have a value first. You can’t check for your password if it doesn’t exist. That’s why I have written password = “”, to give password a value before we check it.

Screenshot 2022-03-14 131645.png
bottom of page