i=0
while ( i< 5):
print(i)
i=i+1
0
1
2
3
4
i=0;
while ( i< 5):
print(i)
i=i+1
else:
print("i am outside the loop")
0
1
2
3
4
i am outside the loop
i=0;
while ( i< 5):
i=i+1
if(i==3):
continue
print(i)
else:
print("i am outside the loop")
1
2
4
5
i am outside the loop
Using break
i=0;
while ( i< 5):
i=i+1
if(i==3):
break
print(i)
else:
print("i am outside the loop")
1
2
i=j=0
while i<5:
while j<5:
print('*',end='')
j=j+1
print("")
j=0
i=i+1
Output
*****
*****
*****
*****
*****
We can use the j value also by updating this line
print(j,end='')
output
01234
01234
01234
01234
01234
num=int(input("Enter the number you want to check : "))
i=2
while(i<num/2):
if(num%i == 0):
print(num, " is not a prime number")
break;
i=i+1
else:
print(num , " is a prime number")
In above code if the condition checked for if became True for any value of i then the break statement will be executed terminating the while loop and the else part of the code will be skipped.
num=100 # Upper limit of prime numbers
i=2
while i<=num-1:
j=2 # start checking each number from 2
while j <= i/2 : # check upto half the number
if(i%j==0): # reminder of division is 0
break # come out of loop without else part
j=j+1
else:
print(i, " is a prime number") # if break is not encountered
i=i+1
user_input = ""
my_sum=0
while user_input != '0':
user_input = input("Enter 0 to quit: ")
my_sum=my_sum + int(user_input)
else:
print("Exited the loop. The sum :", my_sum)
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.