Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python: Iteration Damian Gordon. Python: Iteration We’ll consider four ways to do iteration: – The WHILE loop – The FOR loop – The DO loop – The LOOP.

Similar presentations


Presentation on theme: "Python: Iteration Damian Gordon. Python: Iteration We’ll consider four ways to do iteration: – The WHILE loop – The FOR loop – The DO loop – The LOOP."— Presentation transcript:

1 Python: Iteration Damian Gordon

2 Python: Iteration We’ll consider four ways to do iteration: – The WHILE loop – The FOR loop – The DO loop – The LOOP loop

3 Python: WHILE loop Damian Gordon

4 Python: WHILE loop The WHILE loop works as follows: while CONDITION: STATEMENTS

5 Python: WHILE loop But we’ll do: while CONDITION: # DO STATEMENTS # ENDWHILE;

6 Python: WHILE loop Let’s print out the numbers 1 to 5:

7 # PROGRAM Print1To5: a = 1 while a != 6: # DO print(a) a = a + 1 # ENDWHILE; # END.

8 Python: WHILE loop Let’s print the sum of the numbers 1 to 5:

9 # PROGRAM Sum1To5: a = 1 total = 0 while a != 6: # DO total = total + a a = a + 1 # ENDWHILE; print(total) # END.

10 Python: WHILE loop Let’s do factorial:

11 Python: WHILE loop Let’s do factorial: – Remember: – 5! = 5*4*3*2*1 – 7! = 7*6 *5*4*3*2*1 – N! = N*(N-1)*(N-2)*…*2*1

12 # PROGRAM Factorial: value = int(input("Please input value:")) total = 1 while value != 0: # DO total = total * value value = value - 1 # ENDWHILE; print(total) # END.

13 Python: FOR loop Damian Gordon

14 Python: WHILE loop The FOR loop works as follows: for RANGE: STATEMENTS

15 Python: WHILE loop But we’ll do: for RANGE: # DO STATEMENTS # ENDFOR;

16 Python: FOR loop Let’s remember the program to print out the numbers 1 to 5:

17 # PROGRAM Print1To5: a = 1 while a != 6: # DO print(a) a = a + 1 # ENDWHILE; # END.

18 Python: FOR loop We can do it as follows as well:

19 # PROGRAM Print1To5For: for a in range(1,6): # DO print(a) # ENDFOR; # END.

20 Python: DO loop Damian Gordon

21 Python: DO loop Python doesn’t implement the DO loop. 

22 Python: DO loop But a WHILE loop is OK to do the same thing.

23 Python: LOOP loop Damian Gordon

24 Python: LOOP loop Python doesn’t implement the LOOP loop. 

25 Python: LOOP loop But it does have a BREAK statement, so we can create our own LOOP loop:

26 Python: LOOP loop x = 1 while x == 1: # DO if CONDITION: # THEN break # ENDIF; # ENDWHILE;

27 etc.


Download ppt "Python: Iteration Damian Gordon. Python: Iteration We’ll consider four ways to do iteration: – The WHILE loop – The FOR loop – The DO loop – The LOOP."

Similar presentations


Ads by Google