Skip to content

break, continue and pass keywords

surendrabisht edited this page Jul 11, 2020 · 1 revision

break:

The break statement is used for premature termination of the current loop. We use it with some condition so that when the specified condition arises, control comes out of the loop and loop terminates.

Ex: If we want to return the no n such that the sum of 1 to n will exactly reach above max sum allowed which is 200. We will break the execution as sum reaches 200 or above 200.

i=1
currentSum=0
maxSum=200
while i<=1000:
  if currentSum+i>= maxSum:
      break
  currentSum=currentSum + i
  i=i+1
print(i)

continue:

When continue statement is encountered, current iteration is skipped and further statements in the loop will not execute for current iteration and loop goes back to beginning of the current loop for condition checking and starts next iteration.

used to miss any iteration using some condition in between the n iterations.

Ex. Print 1 to 10 no provided to skip printing digit 5.

i=0
while i<10:
  i=i+1
  if i ==5:
      continue
  print(i)


break continue comparison

break continue


pass:

this keyword is used when you don't have to write any logic but syntactically logic is need at that point. so using this pass keyword will allow to get the code compiled at runtime. Remember as python uses interpreter, code compiled at time of executed.
it can be used a placeholder for code that will be written in future

for x in [0, 1, 2]:
  pass

Clone this wiki locally