-
Book Overview & Buying
-
Table Of Contents
Python Illustrated
By :
With loops, we don’t need to repeat our code like we’ve seen before, because loops are constructs that are meant to repeat a block of code multiple times. We primarily use two types of loops:
while loopsfor loopsIn practice, I find myself using for loops the most. However, let’s start by exploring the while loop since that might be easier for learning.
A while loop executes a block of code as long as a given condition is True. It’s like me when I am chasing a laser pointer (I keep running after it while it’s moving), or Wiesje chasing her tail (she keeps chasing it as long as she believes it’s following her). Here’s what the syntax of a while loop looks like:
while condition:
# Code to execute repeatedly
And again, indentation matters! The code inside the loop must be indented. Let’s print "I love Python!" five times using a while loop...