Foundations of Python

88 / 134

For loop

We can iterate through a set of things such as a list of words, the lines in a file, or a list of numbers. When we have a list of things to loop through, we can construct a definite loop using a for statement. We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.

The syntax of a for loop is similar to the while loop in that there is a for statement and a loop body:

numbers = [1,2,3,4,5]
for number in numbers:
    print number

Suppose there is a list of numbers from 1 to 5 stored in the variable numbers. (Do not worry, we will cover list data type later). Then, we iterate over all the elements of the list and print each of the element. We can do any operation over the elements depending upon the requirement.

Generic Loop process:

  • Initializing one or more variables before the loop starts
  • Performing some computation on each item in the loop body, possibly changing the variables in the body of the loop
  • Looking at the resulting variables when the loop completes

You can try executing the previous exercises using for loop.

No hints are availble for this assesment

Answer is not availble for this assesment

Loading comments...