Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python While Loops.

Similar presentations


Presentation on theme: "Python While Loops."— 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 true condition false statement(s)
in while body

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

5 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

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

7 Example x = 0 while x < 10: print(x**2) x += 1 # Execute above code # What is the output? Why?

8 Another example x = 1 N = 1000 while x < N: print(x) x *= 2 # Execute above code # What is the output? Why?

9 An infinite loop while True: print(“All work and no play makes Jack a dull boy”) # Execute above code # What is the output? Why?

10 How do we exit a loop? You can use the keyword break Example: x = 0
while x < : print(x) if x == 5: break x += 1 What’s happening above? Counter variable “x” increases, but if x == 5, then break exits the loop


Download ppt "Python While Loops."

Similar presentations


Ads by Google