Make delicious recipes!

Loop, break and continue in Python


Following example shows the usage of following:
  1. for
  2. break
  3. continue
  4. while
  5. indentation to define the scope

For loop:

arr = range(5)
print ("arr is " + str(arr))

for v in arr:
  if (v%2 == 0):
    print ("v = " + str(v) + " is even" )
    if (v == 4):
      break
  else:
    print ("v = " + str(v) + " is not even")
    continue

Note: The copy paste from the above may remove the indentation spaces due to which python can give indentation errors. If such a thing happens, then indentation spaces have to be put manually after copy-paste.

Output:

arr is range(0, 5)

v = 0 is even
v = 1 is not even
v = 2 is even
v = 3 is not even
v = 4 is even


Compulsory Indentation:

Not that in the above code, indentation is used to define the scope of a statement.
For example, the 'print' and 'if' statements following first if condition are indented more as compared to the 'if' statement.
This means that these two statements fall under the scope of the if statement.
In other languages like C/Java/Javascript, the same effect is achieved by using curly braces { and }

This approach forces the python code to be better indented.



Same code using while loop:

v = 0

while v < 5:
  v += 1;
  if (v%2 == 0):
    print ("v = " + str(v) + " is even" )
    if (v == 4):
      break
  else:
    print ("v = " + str(v) + " is not even")
    continue


Output:
v = 1 is not even
v = 2 is even
v = 3 is not even
v = 4 is even





Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal