Presentation is loading. Please wait.

Presentation is loading. Please wait.

PYTHON WHILE LOOPS. What you know While something is true, repeat your action(s) Example: While you are not facing a wall, walk forward While you are.

Similar presentations


Presentation on theme: "PYTHON WHILE LOOPS. What you know While something is true, repeat your action(s) Example: While you are not facing a wall, walk forward While you are."— Presentation transcript:

1 PYTHON WHILE LOOPS

2 What you know While something is true, repeat your action(s) Example: While you are not facing a wall, walk forward While you are facing a wall, turn left

3 Flow of a while-loop while condition statement(s) in while body false true

4 Python While Loop Template while CONDITION: #code in while block What’s happening above? 1. If the CONDITION is True, then the code in the while block runs 2. At the end of the while block, the computer automatically goes back to the while CONDITION line 3. It checks if the CONDITION is True, then repeats the while block if it is

5 Example while karel.anyBeepersInBeeperBag(): karel.putBeeper()

6 Another example while karel.nextToABeeper(): karel.pickBeeper()

7 An infinite loop while True: karel.turnLeft()

8 How do we exit a loop? You can use the keyword break Example: while True: if myRobot.facingNorth(): break myRobot.turnLeft() What’s happening above? If the Robot ever faces North, then break exits the loop (skipping the rest of the while block)

9 How do we loop count? How do we run our loop a specific number of times? Loop counters!  It’s just a variable x = 0 Limit the while condition using the loop counter while x < 5: The variable counts the number of times you run x = x + 1

10 Loop counting example x = 0 while x < 5: print(“hello”) x = x + 1 #shortcut: x += 1 What’s happening above? 1. x is initialized to 0, which is less than 5 2. Check if x < 5 is True 3. while block runs (notice that x = x + 1 is indented) 4. x increases to 1 (because 0 + 1 = 1 is saved back in x) 5. Go back up to check if the while condition is True


Download ppt "PYTHON WHILE LOOPS. What you know While something is true, repeat your action(s) Example: While you are not facing a wall, walk forward While you are."

Similar presentations


Ads by Google