Like the break statement, Python supports another statement called the continue statement. It can only appear in the body of a loop. When the compiler encounters a continue statement, then the rest of the statements in the loop are skipped, and the control is unconditionally transferred to the loop-continuation portion of the nearest enclosing loop.
The syntax of the continue statement is given below:
continue
The continue statement cannot be used without an enclosing for or a while loop. When the continue statement is encountered in the while, and for loop, the control is transferred to the code that tests the controlling expression.
The continue statement is used to stop the current iteration of the loop and continues with the next one.
Example 1:
sum=0 n=int(input("Enter the value of n=")) for i in range(1,n+1): number=int(input("Enter the value of number=")) if(number<0): continue else: sum=sum+number print("The sum of positive numbers is=",sum)
Output:
Enter the value of n=5 Enter the value of number=90 Enter the value of number=80 Enter the value of number=-60 Enter the value of number=50 Enter the value of number=20 The sum of positive numbers is= 240
Example 2:
import math while(1): num=int(input("Enter the value=")) if(num==999): break elif(num<0): print("Square root of a negative number can not be calculated") continue else: print("The square root of ",num," is=",math.sqrt(num))
Output:
Enter the value=9 The square root of 9 is= 3.0 Enter the value=8 The square root of 8 is= 2.8284271247461903 Enter the value=-4 Square root of a negative number can not be calculated Enter the value=999
Leave a comment