PYTHON WHILE LOOPS What you know While something

  • Slides: 10
Download presentation
PYTHON WHILE LOOPS

PYTHON WHILE LOOPS

What you know • While something is true, repeat your action(s) • Example: •

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

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

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

Python While Loop Template while CONDITION: #code in while block What’s happening above? 1.

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

Example while karel. any. Beepers. In. Beeper. Bag(): karel. put. Beeper()

Example while karel. any. Beepers. In. Beeper. Bag(): karel. put. Beeper()

Another example while karel. next. To. ABeeper(): karel. pick. Beeper()

Another example while karel. next. To. ABeeper(): karel. pick. Beeper()

An infinite loop while True: karel. turn. Left()

An infinite loop while True: karel. turn. Left()

How do we exit a loop? • You can use the keyword break •

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

How do we loop count? • How do we run our loop a specific

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

Loop counting example x = 0 while x < 5: print(“hello”) x = x

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