-
Step 1
Create a for loop you may wish to break out of early:
for k in range(5,10): -
Step 2
Determine which conditions you wish to test for to see if you want to skip through the loop.
-
Step 3
Use an if statement inside the for loop to skip through the loop early. You may use the continue statement inside the nested if/else statement: for k in range(5,10):
if k > 7:
print 'skipping this iteration!'
continue
print k
This sample loop logic will print: 5
6
skipping the iteration
skipping the iteration
skipping the iteration Note that the final print statement is not inside the if block. -
Step 1
Create a while loop where you may wish to skip through steps:
while True: -
Step 2
Determine which conditions you wish to test for to see if you want to skip through the loop.
-
Step 3
Use an if statement inside the for while to skip through the loop early. You may use the continue statement inside the nested if/else statement:
while True:
my_input = raw_input('Enter a string less than ten characters : ')
if my_input == 'quit':
break
if len(my_input) > 10:
continue
print 'You entered something less than 10 characters'
This loop will continue forever unless the user types "quit", thereby forcing a break statement. If the input that the user enters is greater than 10 characters, it will go back to the top of the while loop, prompting the user for more input. Otherwise, this program will display the string 'You entered something less than ten characters.'











