psajja10

Navigation

Recent site activity

Welcome!‎ > ‎Programming Samples‎ > ‎

Loops

Loops are part of iteration, where an individual can use a computer program and make commands that repeat themselves over and over again without typing the entire program hundreds of times. Iteration uses the Python command and allows users to make complex calculations simpler. For example, the two commands below show how a loop works.

The backloop.py program must list the number ten to one backwards. The way the computer reads the program is: since i>0 and i=10, it will list all the numbers starting from 10. It will read i=10-1=9. Since i=9 and is still greater than 0, the loop will run again. The computer will go through the loop and use i=9 and i=9-1=8. The computer will run through the program gain and use i=8 as the next number and run through the program again. Once i=0, the program will stop because i is no longer greater than 0.

backloop.py

i = 10
while i>0:
    print i
    i=i-1

The following is the total.py program, which is trickier than the backloop.py program. Essentially what this program should do is print the total of all the numbers less than 5. This basic Python program will go through the loop by first looking at the i. Since the value of i=0 and will use the equation i=i+1, when 0 is placed into that equation i=1. And the total will equal 2. Then i=1 will go through the equation again i=2, and the total= 1+2=3. Then i=2, total=6. i=3, total=10,  i=4, total= 15.

total.py

i = 0
total = 0
while i<5:
    i=i+1

    total=total+i
print total