Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPSC 217 T03 Week V Part #1: Iteration Hubert (Sathaporn) Hu.

Similar presentations


Presentation on theme: "CPSC 217 T03 Week V Part #1: Iteration Hubert (Sathaporn) Hu."— Presentation transcript:

1 CPSC 217 T03 Week V Part #1: Iteration Hubert (Sathaporn) Hu

2 Today’s Tutorial Returning A1 TIPS Iteration  While loop  Nested loop  For loop REMINDER: Today is the election day!

3 Returning A1 There are 2 students who got the bonus mark. They will receive +3 on top of what they already have. I won’t identify the winners here. Please check your assignment.  If you win, you will have “Bonus!” on the assignment.  If I think your work is good, it will have “Bonus candidate” on it.

4 TIPS 1.You may and should negotiate with me if you think I have made a mistake. However, since we use grade letter for marking, I will not change your mark unless your grade letter will change. 2.Although I encourage you to talk to me about your mark, in my own experience, your mark won’t likely change. 3.Midterm is coming. Be prepared!

5 Iteration When you want your program to repeat a section of the code, you will need to use iteration. In Python, you can only use 2 kinds of iterations:  While  For

6 While loop Syntax: while condition: body body will be repeated over and over again until condition becomes false. condition is a Boolean expression. TIP: Be wary of the spacing!

7 While loop What does this program do? x = 100 while x > 0: print(x, “ bottles. One fell.”)

8 While loop EXERCISE: Create a program that keeps asking users for a string. The program will only stop when the user enters the correct string. You can make the correct string whatever you want.  For example: Please guess: apple Wrong! Please guess: orange Wrong! Please guess: jackrabbit RIGHT! The program ends!

9 For loop for and while are logically equivalent. However, for does have a nicer syntax for some occasions. Unlike while, you don’t need to declare the variable used for iteration before hand. What does this program do? for x in range(1, 25): print(x, “ people now in the room.”) EXERCISE: Convert the program to use while.

10 Nested loop Did you know that you can put a loop in another? It doesn’t matter if you use for or while. You can nest them in any combination you want. You can nest loop in more than 2 levels. Normally, you use nested loops in order to do something multidimensional…  Like filling a multidimensional array.  Like manipulating a table.

11 Nested loop What does this program do? x = 1 y = 1 while x <= 12: while y <= 12: print (x, “*”, y, “:”, x * y) y += 1 x += 1 y = 0

12 Nested loop EXERCISE: Try out the exercises on loop given on course website.


Download ppt "CPSC 217 T03 Week V Part #1: Iteration Hubert (Sathaporn) Hu."

Similar presentations


Ads by Google