# Loops - continue and break

How to use if and else continue or break with if and else such that the print statement associated with if and else bock after continue or break will work.

Problem:
Declare a integer
for i in range(2, integer)
check whether there is any i that completely divides the integer.
if no print(“Life is good”)

``````num = x
for i in range(2, num):
if num % i != 0:
continue
print("Life is good")

else:
print("Life is anyway good")

How to print "Life is good".``````

If you want to print ‘Life is good’ when the number is not divisible by i (i is any number less than declared integers) then don’t use continue you can simply write your code like below. The below code will it self continue to next iteration of loop once it has checked for if else condition, you don’t need to use continue statement.

``````num = x
for i in range(2, num):
if num % i != 0:
print("Life is good")
else:
print("Life is anyway good")

``````

and if you don’t want to print anything in else clause then don’t include else clause

But I want to first check for all i then print only one time.

Since you are solving the question for finding if a number is prime or not, let’s talk from that perspective.

1. You want to check if any number less than declared integer, divides the declared integer perfectly then declared integer would not be a prime number.
2. So to do this you first iterate through all the numbers between 2 and the declared integer.
3. Then at each number i, you check through if condition what is num%i,
4. if it is not 0 then you want to continue with the loop otherwise you want to print number is not prime. 5. Now don’t think about printing here, in the question i have used an indicator variable, use that. Update its value based on above condition.
5. And as soon as num%i is 0 then use break condition.
The below code shows what condition i am talking about.
``````if num%i == 0:
prime = False
break
``````
1. Now the print statement that you want to do, do it at the end of the loop outside the loop using ‘prime’ variable.

Doing the print inside the for loop will just complicate your code, better to solve it in an easy way using indicator variable.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.