Python While Loop statements

Loops are a useful and commonly used feature in all modern programming languages. A loop is the finest solution for automating a specific repeated operation or preventing yourself from writing repetitive code in your programs. In fact, loops are a collection of instructions that repeat until a condition is met.

Generally, in computer programming, loops are used to repeat a specified code block. This post seeks to teach you how to make a while loop in Python.

Iteration refers to repeatedly running the same code block, maybe multiple times. A loop is a programming structure that implements iteration. There are two forms of repetition in programming:

  • indefinite and
  • definite

Indefinite Iteration

The number of times the loop executes isn’t defined expressly in advance with unlimited iteration. Rather, the selected block is run repeatedly as long as a condition is met.

Definite Iteration

The number of times the targeted block will be executed is provided explicitly when the loop starts with a definite iteration.

Let’s explore how Python loops function more closely.

In Python, what is a while loop?

In Python, the while loop iterates through a code block as long as the test expression (condition) is true. We utilize this loop when we don’t know how many times to iterate ahead of time. Python’s while Loop syntax is as follows:

while test_expression:
    Body of while

The test expression is checked first in the while loop. Only if the test_expression evaluates to True is the loop’s body entered. The test expression is verified again after one cycle. This procedure is repeated until the test_expression returns False.

The body of the while loop in Python is determined by indentation. The body begins with indentation and ends with the first unindented line. Further, any non-zero value in Python is interpreted as True. False is read as None and 0.

The following is an illustration of the while loop using a flowchart.

while loop flowchart in Python

while loop flowchart in Python

In case the condition is not true, the program control is passed to the line after the loop. After a programming construct, all statements indented by the same number of character spaces are part of a single block of code in Python. Python’s way of grouping statements is indentation. The important feature of the while loop here is that it may never run. The loop’s body will be skipped, and the first statement after the while loop will be executed when the condition is tested, and the result is false.

start = 1
while (start < 4):
   print('The variable count is:', start)
   start = start + 1

print("This section runs after the while loop!")

This block consists of print and increment instructions and is repeated until the count is no longer fewer than 4. The index’s current value count is displayed and then increased by 1 with each repetition.

Example: while Loop demo in Python

# Program for adding the natural numbers
# sum = 1+2+3+...+n

# first, request input from the user,
# user_max_bound = int(input("Enter a Maximum value for your while Loop counter: "))

user_max_bound = 5

# initializing the sum_result and counter
sum_result = 0
count = 1

while count <= user_max_bound:
    sum_result = sum_result + count
    count = count+1    # updating the counter

# printing the resultant sum
print("The resulting sum is:", sum_result)

Running the application will produce the following results:

 Program for adding the natural numbers
Program for adding the natural numbers

As long as our counter variable count is less than or equal to user_max_bound, the test phase in the following program will be True (5 in our program). We need to raise the counter variable’s value in the loop’s body. This is vital information (and mostly forgotten). You’ll wind up in an endless (never-ending) loop if you don’t. Finally, the outcome is shown.

While loops are generally accompanied by a variable whose value changes throughout the loop, as you can see from the example above, it also controls when the loop will conclude. You’ll have an infinite loop if you don’t include this line.

The count will not be updated or incremented. Because it will always be set to 1 and remain there, the condition user_max_bound 5 will always be True. This signifies that the loop will keep looping indefinitely.

Using the While loop with else

While loops, like for loops, can have an optional else block. If the condition in the while loop evaluates to False, the else portion is executed. A break statement is used to end the while loop. The else part is ignored in such circumstances. As a result, if no break occurs and the condition is false, the else part of a while loop executes.

Here’s an example to demonstrate.

'''
The while loop is used in this example to demonstrate the use of the else statement.

'''

i = 0

while i < 6:
    print("count loop value:", i)
    i = i + 1
else:
    print("This section runs outside the while loop")

The string inside the while loop is printed five times using a counter variable. The condition in a while turns False on the sixth iteration. As a result, the else section is completed.

Using the Infinite Loop

If a condition never becomes FALSE, the loop becomes infinite. It will help if you exercise caution when utilizing while loops because this condition may never resolve to a FALSE value. As a result, a never-ending cycle is created. An infinite loop is a name for such a loop. In client/server programming, where the server must operate continually so that client applications can communicate with it as needed, an infinite loop may be beneficial.

num = 5
while num == 5 :  # This constructs an infinite loop
   value_entered = raw_input("Please randomly input any number here\n  :")
   print("You entered the following value: ", value_entered)

print("This section executes when done with the while loop!")

The above example enters an infinite loop, and you must exit the program using CTRL+C.

Individual Statement Suites

If your while clause is merely one statement, it can be written on the same line as the while heading. That is similar to the if statement syntax. A one-line while clause has the following syntax and example:

num = 5
while (num): print('The specified counter variable amount is: ', num)
print("This code runs after exiting the while loop!")

It’s best not to try the above example because it runs into an indefinite loop, requiring you to exit using CTRL+C.

Control Statements for Loops

Control statements in loops alter the execution sequence. All automatic objects generated in scope are deleted when execution exits that scope. Python supports the following control statements.

The statement, “Continue.”

The Python Continue Statement restores control to the loop’s beginning. Python while loop with continue statement as an example.

# The following code is responsible for printing all letters the except 'n' and 'u'
start = 0
string_variable = 'codeunderscored'

while start < len(string_variable):
	if string_variable[start] == 'n' or string_variable[start] == 'u':
		start += 1
		continue
		
	print('The Letter now is:', string_variable[start])
	start += 1

The statement, “Break.”

The break statement in Python removes control from the loop. Python while loop with break statement as an example

#  Ensure to break the given loop as soon it sees 'n' # or 'u.'
start = 0
string_variable = 'codeunderscored'

while start < len(string_variable):
	if string_variable[start] == 'n' or string_variable[start] == 'u':
		start += 1
		break
		
	print('The Letter now is: :', string_variable[start])
	start += 1

The Statement, “Pass”

To create empty loops, use the Python pass command. Empty control statements, functions, and classes can also use the pass statement. The following is a Python while loop with a pass statement as an example.

# Demonstrating an empty loop using the pass statement
string_variable = 'codeunderscored'
start = 0

while start < len(string_variable):
	start += 1
	pass

print('The resultant value of start  is:,' start)

Controlled Sentinel Statement

We don’t use a counter variable in this case since we don’t know how many times the loop will run. The user selects how many times the loop should be executed. We use a sentinel value for this. A sentinel value is a number that is used to end a loop whenever a user enters it. The sentinel value is usually -1. The following is a Python while loop with user input as an example.

input_num = int(input('Randomly input any number  of your own choice(-1 to quit): '))

while input_num != -1:
	 input_num = int(input('Randomly input any number  of your own choice(-1 to quit): '))

In the example above, the user is first asked to enter a random number of their choosing. The loop will not execute if the user enters -1. However, the loop’s body executes, and the user is asked for another input again. The user can type -1 to end the loop as many times as possible. In this example, the user has control over how many times he wants to enter data.

Can you nest While Loops?

Python control structures can be layered within one other in general. If/elif/else conditional statements, for example, can be nested:

if age_var < 16:
    if gender_var == 'M':
        print(' You are the son')
    else:
        print('You are the daughter')
elif age_var >= 16 and age_var < 65:
    if gender == 'M':
        print('You must be the father')
    else:
        print('You look like the mother')
else:
    if gender == 'M':
        print('You must be a grandfather')
    else:
        print('You must be somebody's grandmother')

A while loop can also be contained within another while loop, as demonstrated here:

string_array = ['code', 'underscored']
while len(string_array):
    print(string_array.pop(0))
    laptops_array = ['lenovo', 'chrome']
    while len(laptops_array):
        print('>', laptops_array.pop(0))

Within nested loops, a break or continue statement applies to the nearest enclosing loop:

while <expr_one>:
    statement_one
    statement_one

    while <expr_two>:
        statement_two
        statement_two
        break  # The break here is applicable to the while <expr_two>: loop

    while <expr_three>:
        statement_three
        statement_three
        break  # The break here is applicable to the while <expr_three>: loop

    break  # The break here applies to the while <expr_one>: loop

Additionally, while loops and if/elif/else expressions can be nested within each other:

if <expr_one>:
    statement_one
    while <expr_two>:
        statement_two
        statement_two
else:
    while <expr_three>:
        statement_three
        statement_three
    statement_four

Alternative example

while <expr_one>:
    if <expr_two>:
        statement_two
    elif <expr_three>:
        statement_three
    else:
        statement_four

    if <expr_five>:
        statement_five

In fact, you can do a mix and match as you wish all of the Python control structures to your heart’s content. That is exactly how it should be. Consider how aggravating it would be if unanticipated limitations like “A while loop are not contained within an if statement” or “while loops can only be nested four deep inside one another.” You’d have a hard time remembering all of them. Seemingly arbitrary mathematical or logical constraints characterize poor program language design. Fortunately, there aren’t many in Python.

Example: Using else Statement with While Loop

The following example shows how to use an else statement in conjunction with a while statement to print a number if it is less than 10. Otherwise, the else statement is executed.

termination_point = 5
while termination_point < 10:
   print(termination_point, " Values below 10")
   termination_point = termination_point + 1
else:
   print(termination_point, " Values not less than 10")

When the above code is run, the following result is obtained:

Using else Statement with While Loop

Using else Statement with While Loop

Example: Program for printing limited Fibonacci numbers

fib_number = int(input("Please input your Fib Number "))  
# first two intial terms  
first_var = 0  
second_var = 1  

counter = 0  

# ascertain if the given number is either a zero or a negative  
if (fib_number <= 0):  
	print("Wrong Input. Please try again with a valid integer")  
elif ( fib_number == 1):  
	print("The Fibonacci  limit comprises of the sequence upto",limit,":")  
	print(first_var)  
else:  
	print("The fib seq is as follows:")  
while (counter < fib_number) :  
   print(first_var, end = ' ')  
   next_var = first_var + second_var  
   #update the given values  
   first_var = second_var  
   second_var = next_var  
 
   counter += 1  

Example: While loop with else

# program for demonstrating how to use the while-else loop

start = 5
while start < 10:
	start += 1
	print(start)
else: # Because there was no break in for
	print(" Do not Break in\n")

start = 5
while start < 10:
	start += 1
	print(start)
	break
else: # This section of the code is not just executed at all because of the break's presence
	print("The is no Break")

As previously stated, the while loop performs the block till a condition is met. The statement immediately after the loop is performed when the condition turns false. When your while condition is false, the else clause is executed. It will not be run if you exit the loop or raise an exception. Note that the else block immediately following for/while is only run if a break statement does not terminate the loop.

Conclusion

The while loop statement in Python executes a target statement continuously as long as a particular condition is true. When the program’s condition becomes false, the line immediately after the loop is run. While the loop is classified as an indefinite iteration, the number of times the loop is executed isn’t set explicitly in advance, known as indefinite iteration.

We can declare the complete loop in a single line, just like the if block, if the while block consists of a single sentence. Semicolons are used to separate numerous statements in the block that makes up the loop body (;). After a programming construct, all statements indented by the same number of character spaces are regarded to be part of a single block of code. Python’s way of grouping statements is indentation.

When a while loop is run, expr is tested in a Boolean context first, and if true, the loop body is run. The expr is then tested again, and if it remains true, the body is run once more. That is repeated and so on until the expression becomes false.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *