FOR Loops

FOR Loops

FOR loops allow programs to repeat a section of code for a set number of times.

If you know the number of times some code needs to repeat; a FOR loop is perfect.

This loop will display the value of 'i' and increase the value or 'i' until it has done it ten times.

FOR Loops

As Python code:

for i in range(1, 10):
  print(i)

Note:

Like the IF-ELSE you need a colon at the end of the line.

And all the lines of code that are to be repeated must be indented.

Example I

This will output:

for i in range(1, 10):
  print(i)
1
2
3
4
5
6
7
8
9

range(1, 10) will start with 1 but will end before 10.

Example II

This will output:

for i in range(1, 10, 2):
  print(i)
1
3
5
7
9

range(1, 10, 2) will start with 1 but will increase by 2 each time.

Example III

This will output:

for i in range(10, 1, -3):
  print(i)
10
7
4

range(10, 1, -3) will start with 10 and will decrease by 3 each time.

Example IV

This will output:

for letter in 'word':
  print(letter)
w
o
r
d

Steps through each character in the word 'word'.

Tasks I

  1. Ask the user to enter their name and then display their name three times.
  1. Alter program 1 so that it will ask the user to enter their name and a number and then display their name that number of times.
  1. Ask the user to enter their name and display each letter in their name on a separate line.
  1. Change program 3 to also ask for a number. Display their name (one letter at a time on each line) and repeat this for the number of times they entered.

Tasks II

  1. Ask the user to enter a number between 1 and 12 and then display the times table for that number.
  1. Ask for a number below 50 and then count down from 50 to that number, making sure you show the number they entered in the output.
  1. Ask the user to enter their name and a number. If the number is less than 10, and display their name that number of times; otherwise display the message "too high" three times.
  1. Set a variable called total to 0. Ask the user to enter 5 numbers and after each input ask them if they want that number included. If they do, and add the number to the total. If they do not want it included, don't add it to the total, after they have entered all five numbers, display the total.

Tasks III

  1. Ask which direction the user wants to count (up or down). If they select up, then ask them for the top number and then count from 1 to that number. If they select down, ask them to enter a number below 20 and then count down from 20 to that number. If they entered something other than up or down, display the message "I don't understand".
  1. Ask how many people the user wants to invite to a party. If they enter a number below 10, ask for the names and after each name display "[name] has been invited". If they enter a number which is 10 or higher, display the message "too many people".

E For Loops

By David James

E For Loops

Python - FOR Loops

  • 819