Loops
Loops allow us to repeat a block of code multiple times.
There are two types of loops in python: for
loops and while
loops.
For loops
A for
loop goes over each item in a sequence, one by one, repeating the code for each item in
the sequence.
nums = [1,2,3,4,5]
for num in nums:
print(num)
You can create a loop with anything that can be sequenced over, the code below loops through all the characters in the message.
for c in "Foo & Bar":
print(c)
A simple way to create a loop that runs x
number of times is to use the range
function.
for i in range(10):
print(i)
While loops
A while loop runs a code while a condition is true
num = 0
while num < 10:
num = num + 1
Control flow
Loops can be stopped immediately with the break
keyword.
for c in "Hello world":
if c == " ":
print("Found whitespace")
break
The above loop will exit after it finds a white space character. Sometimes instead you want to skip a specific iteration of a loop, for that you can use continue
, which skips the rest of the loop and goes to the next iteration.
characters = []
for c in "Hello world":
if c == " ":
continue
characters.append(c)
print(characters)