JamCoders

💾 Download

Advanced for loop keywords

In [ ]:
# This is a reminder of what a loop looks like

for i in range(20):
    print('still in loop')
print('Loop completed!')
In [ ]:
# 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!')
In [ ]:
# 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!')
In [ ]:
# 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!')

While loops

In [ ]:
# This is the generic syntax for a while loop

while CONTIDION:
    LOOP_BODY
In [ ]:
# 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!')
In [ ]:
# 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!')
In [ ]:
# What is different about this and the one two above?

i = 0
while i < 10:
    i += 1
    print(i)
print('Loop completed!')
In [ ]:
# WARNING!!!!
# You can have loops that run forever.
# These are really really bad.
# Make sure the loop terminates.

while True:
    print('hi!')
In [ ]:
# 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!
In [ ]:
# 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!')
In [ ]:
# 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!')
In [ ]:
# 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
In [ ]:
# What will happen?

i = 0
while True:
    i += 1
    if i > 10:
        break
    print(i)
In [ ]: