# This is a reminder of what a loop looks like
for i in range(20):
print('still in loop')
print('Loop completed!')
# There are two keywords for loops that you will need to know
# The first is "break"
# Break will exit a for loop once it is executed
for i in range(4):
print(i)
if i == 2:
break
print("---")
print('Loop completed!')
# The other keyword you need to know is "continue"
# "continue" will make it so that the rest of the loop body is not executed
# but ONLY for the time it is called
# Notice that "10" is not printed
for i in range(4):
print(i)
if i == 2:
continue
print("---")
print('Loop completed!')
# You can have continue and break in the same loop
for i in range(6):
if i == 2:
continue
if i == 4:
break
print(i)
print('Loop completed!')
# This is the generic syntax for a while loop
while CONTIDION:
LOOP_BODY
# A "while loop" is a loop that executes while CONDITION is true
# The CONDITION is evaluated once the loop body finishes, and only then
i = 0
while i < 10:
print(i)
i += 1
print('Loop completed!')
# If CONDITION is False at the start of the loop, the loop body will not execute!
i = 0
while i < 0:
print(i)
i += 1
print('Loop completed!')
# What is different about this and the one two above?
i = 0
while i < 10:
i += 1
print(i)
print('Loop completed!')
# WARNING!!!!
# You can have loops that run forever.
# These are really really bad.
# Make sure the loop terminates.
while True:
print('hi!')
# WARNING!!!!!
# Even if you don't mean to, the loop can run forever.
# DO NOT do this.
i = 0
while i < 10:
print(i)
print('Loop completed!') # This will never execute!
# You can use "continue" in while loops
# The syntax and behavior is exactly the same as in for loop
i = 0
while i < 10:
i += 1
if i == 5:
continue
print(i)
print('Loop completed!')
# WARNING!!!!
# This loop will also run forever. Why?
# Don't do this.
i = 0
while i < 10:
if i == 5:
continue
print(i)
i += 1
print('Loop completed!')
# You can also use "break" in while loops
# The syntax and usage is exactly the same as in for loops
i = 0
while True:
if i > 10:
break
print(i)
i += 1
# What will happen?
i = 0
while True:
i += 1
if i > 10:
break
print(i)