Tuesday 16 October 2012

Using for loops in Python


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
Now count from 0 to 9 using only 1 value
Count to 20 from 2 in 2's
Count from 10 to 1

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

No comments:

Post a Comment