Learning to Program in Python for Kids

of all ages  by Philip M Russell

The Basic For Loop

an image

The for loop is much simpler in Python than in most other languages

for count in range(0,5)

The function range( ) is called with three arguments:

range ( start, end, step)

Problems to Solve

an image

Lets try some exercises.

Write a program to count from 1 to 10

Answer 1

Now count from 0 to 9 using only 1 value

Answer 2

Count from 2 to 20 in 2's

Answer 3

Count from 10 to 1

Answer 4

Making the loop interesting

                                        Lets look at some different type of code
                                
                        
                
         #!/usr/bin/env python
                  list = [2,4,6,8,10]
                  total = 0
                  for num in list:
                      total = total + num
                  print ("The total is: %d" % total)
                        
                
                
                
So what does this code do? We have a list of items. These numbers are stored in a
large variable called an array. This array can hold many different values not just one.
As we go through the for loop, the loop first looks at the first item in the list then
the next then the next and so on, Each time the loop is repeated it looks at the next
item in the list.

  • Python is good at using for loops in a different way to other languages.
  • We will look at more in a later lesson
an image

For loops are available in most languages and are used when you know how many times you want to do something. The loops can go forwards as well as backwards