python for else




        In other programing language we use  else statement/condition  with if  i.e. if else ,else is used to execute a code when condition of if block become false ,These are the conditional statement use to execute code base on  different conditions
Q. for loop with  else is possible in python ?
-Ans: Yes 
               Python allows to use else statement with for as well as while loop ,In python we can use for         and else together .to use this two statement together we need one control statement i.e. break
        and the else block will execute only when the for loop is not terminated by break statement 

e.g.
    Q. Write a code to print a number(first number only) from given list which is divisible by 3, If A              number which is  divisible by 3 is not there in list  then print Invalid data ?
          l ={2,7,9,33,55,99,} 
_ Solution 
                      

l ={2,7,33,55,99}
for a in l:
    if a % 3 == 0:
          print(a)
          break
else:
("Invalid data")

Output =33
use print() function after else block 


In above code if we not use  the break statement ,then it will  print all the number those are divisible by 3,loop will not get terminated it will check the  condition for every number in list and print all numbers in list which are divisible by 3 



use print() function after else block 
  
In the above code , if the indentation of else block is  not accurate ,or we put else block with respect to if block and assume  there is no number in list which is divisible by 3,then compiler execute the else block for 5 times i.e. Total number in given list.




so to execute else statement in for else loop  properly indentation is very important .

And that's all about for else block  

I hope this article on for else block is helpful for u …..


Thank u.. 😊