Computer Studies‎ > ‎Python‎ > ‎Python Tutorial‎ > ‎

For Loops

Another kind of loop is the "for" loop, which, as previously mentioned, is used when you know exactly how many times you need the loop to execute. The number of times, and the values of the loop counter, are specified as shown below:

for i in range (1,5):
    print ("The index counter is", i)
print ("All done!")

The output of this example looks like this:

The index counter is 1
The index counter is 2
The index counter is 3
The index counter is 4
All done!

Just like with the while loop, the lines that are executed in the loop are determined by which lines are indented. In the example above, the the loop counter ("I") equals "1" in the first iteration (as designated by the first argument in the for loop), then 2, then 3, then 4. Note that the loop then stops; it does not execute the loop for "5", as you would first think by the example. Think to yourself that the loop starts at 1 and runs as long as it is less than 5.

Here's another example, but this time only printing every 2nd number:

for i in range (1,10,2):
    print ("The index counter is", i)
print ("All done!")

The third argument in the for loop (the "2") is the step size, which tells Python to iterate the loop by 2's. The output from this loop looks like this:

The index counter is 1
The index counter is 3
The index counter is 5
The index counter is 7
The index counter is 9
All done!

Assignment

Modify program 023 so that it uses a for loop instead of a conditional loop.

Save as "024.py".

Assignment

Modify program 023a so that it uses a for loop instead of a conditional loop.

Save as "024a.py".

Assignment

Write a program that prompts for an initial amount of money and an annual interest rate, then calculates how much money will be accumulated in 20 years.

Save as "024b.py".

Assignment

Write a program that prompts for a starting temperature temp1 and ending temperature temp2, then prints a neatly formatted Celsius to Fahrenheit conversion table, printing one conversion every 5 degrees.

Save as "024c.py".

Assignment

Modify the above temperature conversion program so it converts from Fahrenheit to Celsius. 

Save as "024d.py".

Assignment

Write a program that prompts for a number n, then prints the factorial (n!) of that number.

Save as "024e.py".

Supplemental Assignment

Write a program that prompts for a number n, then prints the nth Fibonacci number.

Save as "024f.py".



Comments