Difference between revisions of "Iteration - Python"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Created page with "=Types of Iteration / Loop= Programming languages tend to have different types of iteration available, for example you have: For, Repeat, While. *For – will run a set numbe...")
(No difference)

Revision as of 10:23, 21 June 2018

Types of Iteration / Loop

Programming languages tend to have different types of iteration available, for example you have: For, Repeat, While.

  • For – will run a set number of times
  • Repeat – will run at least once and then check
  • While – will check first so may never run

For

Should be used when you need to repeat a certain number of times. This could be a known value such as ten times or a value we can calculate (for example 10 items a list, a bubble sort will definitely sort the list with a loop of 10 iterations and we need to repeat the loop 10 times).

In Python, for loop is usually used with the range() function, so to print a number from 1 to 10:

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

The value of i will initially be 1 (specified in the range command), it will then increment this by 1 each time the loop is repeated. So the fourth time through this loop i will equal 4. Essentially the value 11 is the stopping condition, ie repeat while i is less than 11.

Alternatively you could give range a single value, in this case it will start from 0. So the code below will print out the numbers from 0 to 9:

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

For Loop & Lists

A for loop can be used to cycle through each item in a list. This could be extremely useful in many situations:

num_list = [1,3,5,7,9,11]
total=0
for num in num_list:
     total = total + num
print("total is "+total)

Now Try

  1. Create a program to print out the 12 times table (using a for loop)
  2. Create a program to draw the number of stars entered by the user (these should be on a single row)
  3. Adapt the line of stars program above to print the stars the number of times the user entered (ie 2 lines of 2 stars)
  4. Create a program to draw a triangle of stars