<jupyter_start><jupyter_text>All the IPython Notebooks in **Python Flow Control Statements** lecture series by Dr. <NAME> are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**  Loops in PythonLoops in Python programming function similar to loops in C, C++, Java or other languages. Python loops are used to repeatedly execute a block of statements until a given condition returns to be **`False`**. In Python, we have **two types of looping statements**, namely:  Python `while` LoopLoops are used in programming to repeat a specific block of code. In this article, you will learn to create a **`while`** loop in Python. We use a **`while`** loop when we want to repeat a code block.  What is `while` loop in Python?The **`while`** loop in Python is used to iterate over a block of code as long as the  expression/condition is **`True`**. When the condition becomes **`False`**, execution comes out of the loop immediately, and the first statement after the **`while`** loop is executed.We generally use this loop when we don't know the number of times to iterate beforehand.Python interprets any non-zero value as **`True`**. **`None`** and **`0`** are interpreted as **`False`**.  Why and When to use `while` loop in PythonNow, the question might arise: when do we use a **`while`** loop, and why do we use it.* **Automate and repeat tasks:** As we know, **`while`** loops execute blocks of code over and over again until the condition is met it allows us to automate and repeat tasks in an efficient manner.* **Indefinite Iteration:**The **`while`** loop will run as often as necessary to complete a particular task. When the user doesn’t know the number of iterations before execution, **`while`** loop is used instead of a **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)** loop* **Reduce complexity:** **`while`** loop is easy to write. using the loop, we don’t need to write the statements again and again. Instead, we can write statements we wanted to execute again and again inside the body of the loop thus, reducing the complexity of the code* **Infinite loop:** If the code inside the **`while`** loop doesn’t modify the variables being tested in the loop condition, the loop will run forever.  Syntax: ```pythonwhile condition:    body of while loop```1. In the **`while`** loop, expression/condition is checked first.2. The body of the loop is entered only if the expression/condition evaluates to **`True`**.3. After one iteration, the expression/condition is checked again. This process continues until the test_expression evaluates to **`False`**.>**Note:** An infinite loop occurs when a program keeps executing within one loop, never leaving it. To exit out of infinite loops on the command line, press **CTRL + C**.<jupyter_code># Example 1: Print numbers less than 5

count = 1
# run loop till count is less than 5
while count < 5:
    print(count)
    count = count + 1
# Example 2:

num = 10
sum = 0
i = 1
while i <= num:
    sum = sum + i
    i = i + 1
print("Sum of first 10 number is:", sum)
# Example 3:

a=10        # 'a' is my variable

while a>0:  # Enter the body of while loop because condition is TRUE
    print (("Value of a is"),a)
    a=a-2
print ("Loop is Completed")
# Example 4:

n=153
sum=0

while n>0:
    r=n%10   # r is the remainder of the division
    sum+=r   # sum+=r is equal to sum = sum+r
    n=n/10
print (sum)
# Example 5: How many times a given number can be divided by 3 before it is less than or equal to 10.

count = 0
number = 180
while number > 10:
    # divide number by 3
    number = number / 3
    # increase count
    count = count + 1
print('Total iteration required', count)
# Example 6: Program to add natural numbers up to sum = 1+2+3+...+n

# To take input from the user, 
# n = int(input("Enter n: "))

n = 10

# initialize sum and counter
sum = 0
i = 1

while i <= n:
    sum = sum + i
    i = i+1    # update counter, i.e., the value of i will change from 1 to 2 in next iteration...

# print the sum
print("The sum is", sum)<jupyter_output>The sum is 55<jupyter_text>**Explanation:**In the above program, the test expression will be **`True`** as long as our counter variable **`i`** is less than or equal to **`n`** (10 in our program).We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).Finally, the result is displayed.<jupyter_code># Example 7: simple fibonacci series
# the sum of two elements defines the next set

a, b = 0, 1
while b < 1000:
    print(b, end = ' ', flush = True)
    a, b = b, a + b

print() # line ending<jupyter_output>1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987<jupyter_text>`while` loop with `if-else`A **`while`** loop can have an optional **[if-else](https://github.com/milaan9/03_Python_Flow_Control/blob/main/002_Python_if_else_statement.ipynb)** block. We use **`if-else`** statement in the loop when conditional iteration is needed. i.e., If the condition is **`True`**, then the statements inside the if block will execute othwerwise, the else block will execute.<jupyter_code># Example 1: Print even and odd numbers between 1 to the entered number.

n = int(input('Please Enter Number '))
while n > 0:
    # check even and odd
    if n % 2 == 0:
        print(n, 'is a even number')
    else:
        print(n, 'is a odd number')
    # decrease number by 1 in each iteration
    n = n - 1
# Example 2: printing the square of odd numbers less than n. 

n =10
i = 1
while i < n:
    #if (i % 2 == 0): (for even numbers)
    if (i % 2 != 0):
        print(i ** 2)
        i = i + 1
    else:
        print(i)
        i = i + 1
# Example 3: Add all even numbers from 1 to 10 using while loop
# 2+4+6+8+10

# n = int(input("Please enter the maximum value: "))
n = 10

sum = 0
i = 1

while i <= n:
    if(i%2==0):
        sum = sum + i
#        sum += i
    i = i+1
    
# print the sum
print("The sum is", sum)
# Example 4: Write a code to add all the prime numbers between 17 to 53 using while loop
# 17, 19, 23, 29, 31, 37, 41, 43, 47, 53

'''Method 1'''

sum=0
for i in range(17,54):
    k=2
    if i>=2:
        while i % k!=0:
            k+=1
        if i==k:
            sum += i
            print(i)
print("The total sum is",sum)<jupyter_output>17
19
23
29
31
37
41
43
47
53
The total sum is 340<jupyter_text>`while` loop with `else`A **`while`** loop can have an optional **`else`** block as well. The **`else`** part is executed if the condition in the **`while`** loop evaluates to **`False`**.The **`else`** will be skipped/ignored when:* **`while`** loop terminates abruptly* The **[break statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** is used to break the **`while`** loop<jupyter_code>count = 0
while count < 5:
    print(count)
    count = count + 1
else:
    print(count)<jupyter_output>0
1
2
3
4
5<jupyter_text>**Explanation:**The above loop condition will be false when count is 5 and the loop stops, and execution starts the else statement. As a result 5 will be printed.<jupyter_code># Example 1: Use while loop to print numbers from 1 to 6

i = 1
while i <= 6:
    print(i)
    i = i + 1
else:
    print("Done. 'while loop' executed normally")
# Example 2: Else block with break statement in a while loop.

i = 1
while i <= 6:
    print(i)
    if i == 3:
        break
    i = i + 1
else:
    print("Done. `while loop` executed normally")
# Example 3:
'''Example to illustrate the use of else statement with the while loop'''

counter = 0  # counter is my variable

while counter < 3:
    print("Inside while loop")
    counter = counter + 1  # increment the counter
else:
    print("Inside else")<jupyter_output>Inside while loop
Inside while loop
Inside while loop
Inside else<jupyter_text>**Explanation:**Here, we use a **`counter`** variable to print the string **`Inside loop`** three times.On the fourth iteration, the condition in **`while`** becomes **`False`**. Hence, the **`else`** part is executed.<jupyter_code># Example 4: we want a user to enter any number between 100 and 600

number = int(input('Enter any number between 100 and 600 '))
# number greater than 100 and less than 600
while number < 100 or number > 600:
    print('Incorrect number, Please enter correct number:')
    number = int(input('Enter a Number between 100 and 600 '))
else:
    print("Given Number is correct", number)<jupyter_output>Enter any number between 100 and 600 555
Given Number is correct 555<jupyter_text>Using Control Statement in `while` loops in Python**[Control statements](https://github.com/milaan9/03_Python_Flow_Control/blob/main/007_Python_break_continue_pass_statements.ipynb)** in Python like **`break`**, **`continue`**, etc can be used to control the execution flow of **`while`** loop in Python. Let us now understand how this can be done.It is used when you want to exit a loop or skip a part of the loop based on the given condition. It also knows as **transfer statements**.  a) `break` in `while` loopUsing the **`break`** statement, we can exit from the **`while`** loop even if the condition is **`True`**. If the **`break`** statement is used inside a nested loop (loop inside another loop), it will terminate the innermost loop. For example,<jupyter_code># Example 1:

count = 0
while count < 5:
    print(count)
    count = count + 1
    if count == 3:
        break<jupyter_output>0
1
2<jupyter_text>**Explanation**: Here, the **`while`** loop runs until the value of the variable **`i`** is less than 5. But because of the **`break`** statement, the loop gets terminated when the value of the variable **`i`** is 3 and it prints 0, 1, 2<jupyter_code># Example 2:

list = [60, "HelloWorld", 90.45, 50, 67.23, "Python"]  # total 6 elements
i = 0
while(i < 6):
    print(list[i])
    i = i + 1
    if(i == 3):
        break<jupyter_output>60
HelloWorld
90.45<jupyter_text>**Explanation**: Here, the **`while`** loop runs until the value of the variable **`i`** is less than 6. But because of the **`break`** statement, the loop gets terminated when the value of the variable **`i`** is 3.<jupyter_code># Example 3: Display each character from a string and if `a` character is number then stop the loop.

name = 'Alan99White'
size = len(name)
i = 0
# iterate loop till the last character
while i < size:
    # break loop if current character is number
    if name[i].isdecimal():
        break;
    # print current character
    print(name[i], end=' ')
    i = i + 1<jupyter_output>A l a n<jupyter_text>b) `continue` in while loopThe **`continue`** statement is used to stop/skip the block of code in the loop for the current iteration only and continue with the next iteration. For example, let's say you want to print all the odd numbers less than a particular value. Here is how you can do it using **`continue`** keyword in Python.<jupyter_code># Example 1:

count = 0
while count < 5:
    if count == 3:
        continue        
    else:
        print(count)
        count = count + 1<jupyter_output>0
1
2<jupyter_text>**Explanation:**The above **`while`** loop only prints 0, 1, 2 and 4 (skips 3).<jupyter_code># Example 2: printing odd numbers less than `n`

n=10
i = 1
while (i < n):
    if (i % 2 == 0):
        i = i + 1
        continue  # continue means skip the current loop
    else:
        print (i)
        i = i + 1<jupyter_output>1
3
5
7
9<jupyter_text>**Explanation:**Here, the **`continue`** statement gets executed when the value of the variable is an even number. This simply means, whenever it is an even number, we simply skip all other statements and execute the next iteration.<jupyter_code># Example 3: Write a while loop to display only alphabets from a string.

name = 'Alan99White'

size = len(name)
i = -1
# iterate loop till the last character
while i < size - 1:
    i = i + 1
    # skip while loop body if current character is not alphabet
    if not name[i].isalpha():
        continue
    # print current character
    print(name[i], end=' ')<jupyter_output>A l a n W h i t e<jupyter_text>c) `pass` in `while` loopThe **`pass`** statement is a null statement, i.e., nothing happens when the statement is executed. Primarily it is used in empty functions or classes. When the interpreter finds a pass statement in the program, it returns no operation.<jupyter_code># Example 1:

n = 4
while n > 0:
    n = n - 1
    pass<jupyter_output><empty_output><jupyter_text>Reverse `while` loopA reverse loop means an iterating loop in the backward direction. A simple example includes:* Display numbers from 10 to 1.* Reverse a string or list<jupyter_code># Example 1: Reverse a while loop to display numbers from 10 to 1

# reverse while loop
i = 10
while i >= 0:
    print(i, end=' ')
    i = i - 1<jupyter_output>10 9 8 7 6 5 4 3 2 1 0<jupyter_text>Nested `while` loops**Nested while loop** is a **`while`** loop inside another **`while`** a loop. In the nested **`while`** loop, the number of iterations will be equal to the number of iterations in the outer loop multiplied by the iterations in the inner loop. In each iteration of the outer loop inner loop execute all its iteration.**Syntax:**```pythonwhile expression:    while expression:        statement(s)    statement(s)```  `while` loop inside `while` loop  Example: Nested `while` loop<jupyter_code># Example: print the first 10 numbers on each line 5 times

i = 1
while i <= 3:
    j = 1
    while j <= 10:
        print(j, end='')
        j = j + 1
    i = i + 1
    print()<jupyter_output>12345678910
12345678910
12345678910<jupyter_text>Example: Nested `while` loop to print the pattern```python** ** * ** * * ** * * * *```<jupyter_code># Example 1: Method 1

i = 1
# outer while loop
# 5 rows in pattern
while i < 6:
    j = 0
    # nested while loop
    while j < i:
        print('*', end=' ')
        j = j + 1
    # end of nested while loop
    # new line after each row
    print('')
    i = i + 1<jupyter_output>* 
* * 
* * * 
* * * * 
* * * * *<jupyter_text>`for` loop inside `while` loopWe can also use **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)** inside a **`while`** loop as a nested loop. For example,<jupyter_code># Example 1: Method 2

i = 1
# outer while loop
while i < 6:
    # nested for loop
    for j in range(1, i + 1):
        print("*", end=" ")
    print('')
    i = i + 1
# Example 2: Write a code to add all the prime numbers between 17 to 53 using while loop
# 17, 19, 23, 29, 31, 37, 41, 43, 47, 53

'''Method 1'''

n=17
sum=0
while n<=53:
    for i in range(2,n):
        if(n % i)== 0: 
            break
        else:
            i=i+1
    else:
        sum=sum+n
        print(n)
    n=n+1
print("The total sum is",sum)
# Example 3:

print('Show Perfect number fom 1 to 100')
n = 2

while n <= 100:            # outer while loop
    x_sum = 0    
    for i in range(1, n):  # inner for loop
        if n % i == 0:
            x_sum += i
    if x_sum == n:
        print('Perfect number:', n)
    n += 1<jupyter_output>Show Perfect number fom 1 to 100
Perfect number: 6
Perfect number: 28<jupyter_text>Iterate String using `while` loopBy looping through the **[string](https://github.com/milaan9/02_Python_Datatypes/blob/main/002_Python_String.ipynb)** using **`while`** loop, we can do lots of string operations. For example,<jupyter_code># Example 1: while loop to iterate string letter by letter

name = "Alan"
i = 0
res = len(name) - 1
while i <= res:
    print(name[i])
    i = i + 1<jupyter_output>A
l
a
n<jupyter_text>Iterate List using `while` loop**[Python list](https://github.com/milaan9/02_Python_Datatypes/blob/main/003_Python_List.ipynb)**  is an ordered collection of items of different data types. It means Lists are ordered by index numbers starting from 0 to the total items-1. List items are enclosed in square **`[]`** brackets.Below are the few examples of Python list.```python>>> numers = [1,2,4,6,7]>>> players = ["Messi", "Ronaldo", "Neymar"]```Using a loop, we can perform various operations on the list. There are ways to iterate through elements in it. Here are some examples to help you understand better.<jupyter_code># Example 1: Use while loop to iterate over a list.

numbers = [1, 2, 3, 6, 9]
size = len(numbers)
i = 0
while i < size:
    print(numbers[i])
    i = i + 1
# Example 2: printing the first two elements of a list

list = [60, "HelloWorld", 90.96]  # list with three elements
i = 0
while(i < 2):
    print (list[i]) #printing the element in the index i
    i = i + 1<jupyter_output>60
HelloWorld<jupyter_text>>**Note**: When working with the **`while`** loop, it is important to declare the indexing variable **`i`** beforehand and to increment the indexing variable accordingly. Else it will result in an infinite loop.  Iterate Numbers using `while` loopNow, consider a program where you want to print out the squares of all the **[numbers](https://github.com/milaan9/02_Python_Datatypes/blob/main/001_Python_Numbers.ipynb)** less a particular number. Let's see how this works with a while statement.<jupyter_code># Example 1: printing the square of numbers less than `n`

i = 1
while (i <= 10):
    print (i ** 2) #printing the element in the index i
    i = i + 1
# Example 2: Find the cube of number from 1 to 9.

i = 1
while(i<10):
    print(i*i*i)
#   print(i**3)
    i=i+1
# Example 3:

i = 1
while i < 3:
    print(i ** 2)
    i = i+1
print('Loop over')<jupyter_output>1
4
Loop over
{'fraction_non_alphanumeric': 0.11176269642450466, 'fraction_numerical': 0.033022090639945344, 'mean_word_length': 3.5422808378588053, 'pattern_counts': {'":': 0, '<': 93, '<?xml version=': 0, '>': 79, 'https://': 9, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '20', 'dir': 'jupyter-structured-clean-dedup', 'id': '185447', 'license': 'MIT', 'n_tokens_mistral': 6023, 'n_tokens_neox': 5449, 'n_words': 2499, 'path': '006_Python_while_Loop.ipynb', 'repo_name': 'ATrain951/02.python_flowcontrol-milaan', 'size': '17571'}