Python else suite

In Python, it is possible to use 'else' statement along with for loop or while loop in the form shown in Table:

for with else syntax

CopiedCopy Code

for( var in sequence)
    statements
else:
    statements

while with else syntax

CopiedCopy Code

while( condition ):
    statements
else:
    statements

The else suite will be always executed irrespective of the statements in the loop are executed or not.

CopiedCopy Code

for i in range(5): 
   print("Yes") 
else: 
print("No")

Output:

CopiedCopy Code

Yes
Yes
Yes
Yes
Yes
No

It means, the for loop statement is executed and also the else suite is executed.

A Python program to search for an element in the list of elements.

CopiedCopy Code

group1 = [1,2,3,4,5]
search = int(input('Enter element to search:')) 
for element in group1: 
   if search == element: 
print('Element found in group') 
      break #come out of for loop 
else: 
print('Element not found in group1') #this is else suite

Write a python program to check whether given number is Prime number or not?

CopiedCopy Code

num = int(input("Enter a number: "))  
if num > 1:  
   for i in range(2,num):  
       if (num % i) == 0:  
print(num,"is not a prime number")  
           print(i,"times",num//i,"is",num)  
           break  
   else:  
print(num,"is a prime number")  
else:  
print(num,"is not a prime number")

Write a python program to list of Prime numbers

CopiedCopy Code

lower = int(input("Enter starting number : "))  
upper = int(input("Enter ending number: "))  
for num in range(lower,upper + 1):  
   if num > 1:  
       for i in range(2,num):  
           if (num % i) == 0:  
               break  
       else:  
          print(num,end='\t')