Topics
While Loop Structure
In programming, while loop is usually used to perform some repetitive tasks that may be executed one or more times based on some condition. The code below shows a sample while loop in Python:
# usually has a control variable to start the while loop i = 0 # terminating condition: while loop will terminate if i >= 10 while i < 10: # changing the value of the control variable i += 2 print i #output: 2 4 6 8 10
Using break statement
You can use the break statement to cause early termination. The break statement causes the execution to immediately exit the while block and continue with the next statement after the while block, if any.
i = 0 while i < 10: i += 2 if i>5: # exit 'while' loop if i is greater than 5 break print i #output: 2 4
Using continue statement
You can use the continue statement to skip certain iteration. The continue statement causes the execution to skip the rest of the statements within the while block for that iteration.
i = 0 while i < 10: i += 2 if i==4: # next 'print' statement is # skipped when i equals 4. continue print i #output: 2 6 8 10
Code Snippets
This section will contain some code snippets to show some practical use of the topic that you have learnt.
# Printing patterns # while loop version # ------------------- + + + + + + + + + + + + + + + i = 1 while i < 6: print i * '+ ' i = i + 1 # Adding numbers from user input # ------------------------------ x = input("Enter a number (-9 to end) :") total = 0 while x != -9: total = total + x x = input("Enter a number (-9 to end) :") print "Total: ", total # Sample output >>> Enter a number (-9 to end) :2 >>> Enter a number (-9 to end) :4 >>> Enter a number (-9 to end) :3 >>> Enter a number (-9 to end) :-9 Total: 9