Learn Python – Python While loop- Basic and advance

The Python while loop lets in a phase of the code to be achieved till the given situation returns false. It is also acknowledged as a pre-tested loop.

It can be considered as a repeating if statement. When we do not recognize the variety of iterations then the while loop is most tremendous to use.

The syntax is given below.

while expression:    
    statements    

Here, the statements can be a single declaration or a crew of statements. The expression need to be any valid Python expression resulting in authentic or false. The actual is any non-zero value and false is zero

While loop Flowchart

Loop Control Statements

We can alternate the regular sequence of while loop’s execution the usage of the loop control statement. When the while loop’s execution is completed, all automatic objects described in that scope are demolished. Python affords the following manipulate statement to use inside the whilst loop.

  1. Continue Statement – When the continue declaration is encountered, the manage transfer to the opening of the loop. Let’s recognize the following example.

Example:

# prints all letters except 'a' and 't'   
i = 0  
str1 = 'javatpoint'  
  
while i < len(str1):   
    if str1[i] == 'a' or str1[i] == 't':   
        i += 1  
        continue  
    print('Current Letter :', a[i])   
    i += 1  

Output:

Current Letter : j
Current Letter : v
Current Letter : p
Current Letter : o
Current Letter : i
Current Letter : n

two Break Statement – When the damage assertion is encountered, it brings control out of the loop.

Example:

# The control transfer is transfered  
# when break statement soon it sees t  
i = 0  
str1 = 'javatpoint'  
  
while i < len(str1):   
    if str1[i] == 't':   
        i += 1  
        break  
    print('Current Letter :', str1[i])   
    i += 1  

Output:

Current Letter : j
Current Letter : a
Current Letter : v
Current Letter : a

3 Pass Statement – The bypass statement is used to declare the empty loop. It is additionally used to define empty class, function, and manipulate statement. Let’s recognize the following example.

Example –

# An empty loop   
str1 = 'javatpoint'  
i = 0  
  
while i < len(str1):   
    i += 1  
    pass  
print('Value of i :', i)  

Output:

Value of i : 10

Example-1: Program to print 1 to 10 using whilst loop

i=1  
#The while loop will iterate until condition becomes false.  
While(i<=10):    
    print(i)   
    i=i+1   

Output:

1
2
3
4
5
6
7
8
9
10

Example -2: Program to print desk of given numbers.

i=1    
number=0    
b=9    
number = int(input("Enter the number:"))    
while i<=10:    
    print("%d X %d = %d \n"%(number,i,number*i))    
    i = i+1    

Output:

Enter the number:10
10 X 1 = 10 

10 X 2 = 20 

10 X 3 = 30 

10 X 4 = 40 

10 X 5 = 50 

10 X 6 = 60 

10 X 7 = 70 

10 X 8 = 80 

10 X 9 = 90 

10 X 10 = 100 

Infinite while loop

If the circumstance is given in the while loop in no way turns into false, then the while loop will by no means terminate, and it turns into the endless while loop.

Any non-zero price in the whilst loop suggests an always-true condition, whereas zero shows the always-false condition. This kind of approach is useful if we desire our program to run constantly in the loop except any disturbance.

Example 1

while (1):    
    print("Hi! we are inside the infinite while loop")  

Output:

Hi! we are inside the infinite while loop
Hi! we are inside the infinite while loop

Example 2

var = 1    
while(var != 2):    
    i = int(input("Enter the number:"))    
    print("Entered value is %d"%(i))    

Output:

Enter the number:10
Entered value is 10
Enter the number:10
Entered value is 10
Enter the number:10
Entered value is 10
Infinite time

Using else with while loop

Python permits us to use the else statement with the while loop also. The else block is finished when the condition given in the while statement becomes false. Like for loop, if the whilst loop is broken the use of ruin statement, then the else block will not be executed, and the assertion existing after else block will be executed. The else statement is optional to use with the while loop. Consider the following example.

Example 1

i=1   
while(i<=5):    
    print(i)    
    i=i+1    
else:  
    print("The while loop exhausted")    

Example 2

i=1    
while(i<=5):    
    print(i)    
    i=i+1    
    if(i==3):    
        break   
else:  
    print("The while loop exhausted")  

Output:

1
2

In the above code, when the ruin declaration encountered, then whilst loop stopped its execution and skipped the else statement.

Example-3 Program to print Fibonacci numbers to given restrict

terms = int(input("Enter the terms "))  
# first two intial terms  
a = 0  
b = 1  
count = 0  
  
# check if the number of terms is Zero or negative  
if (terms <= 0):  
   print("Please enter a valid integer")  
elif (terms == 1):  
   print("Fibonacci sequence upto",limit,":")  
   print(a)  
else:  
   print("Fibonacci sequence:")  
   while (count < terms) :  
       print(a, end = ' ')  
       c = a + b  
       # updateing values  
       a = b  
       b = c  
     
    count += 1  

Output:

Enter the terms 10
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34