Python while Loop | Linuxize

[ad_1]

Loops are one of the fundamental concepts of programming languages. Loops are handy when you want to repeat a specific block of code a number of times until a given condition is met.

There are two basic loop constructs in Python, for
and while loops.

This tutorial covers the basics of while loops in Python. We’ll also show you how to use the else clause and the break and continue statements.

Python while Loop #

The while loop executes its statements an unknown number of times as long as the given condition evaluates to true.

The Python while loop takes the following form:

while EXPRESSION:
    STATEMENT(S)

The while statement starts with the while keyword, followed by the conditional expression.

The EXPRESSION is evaluated before executing the statements. If the condition evaluates to true, the STATEMENT(S) is executed. Otherwise, if the condition evaluates to false, the loop is terminated, and the program control is passed to the statement that follows.

The STATEMENT(S) block starts with an indentation and ends with the first unindented line. Most people choose to use either 4-space or 2-space indentation. The official Style Guide for Python Code
recommends to use 4-spaces per indentation level and to avoid mixing the use of tabs and spaces for indentation.

Let’s look at the following example code that increments and prints the current value of the variable i as long as it is less than five:

i=0
while i < 5:
    i += 1
    print('number:', i)

Tue loop iterates as long as i is less or equal to five. It will produce the following output:

number: 1
number: 2
number: 3
number: 4
number: 5

Python supports standard comparison operations:

  • a == b – True if a and b are equal.
  • a != b – True if a and b are not equal.
  • a > b – True if a is greater than b.
  • a >= b – True if a is equal or greater than b.
  • a < b – True if a is less than b.
  • a <= b – True if a is equal or less than b.

To negate the conditional expression, use the logical not operator:

i=0
while not i >= 5:
    i += 1
    print('number:', i)

break and continue Statements #

The break and continue statements allow you to control the while loop execution.

The break statement terminates the current loop and passes program control to the statement that follows the terminated loop. The most common situation is to use break to terminate the loop when a certain condition is met.

In the following example, the execution of the loop is interrupted once the current iterated item is equal to 2.

i=0
while i < 5:
    i += 1
    if i == 2:
        break
    print('number:', i)
Number: 1

The continue statement exits the current iteration of a loop and passes program control to the loop’s next iteration.

i=0
while i < 5:
    i += 1
    if i == 2:
        continue
    print('number:', i)
number: 1
number: 3
number: 4
number: 5

else Clause #

Unlike other languages, in Python, the while loop has an optional else clause:

while EXPRESSION:
    STATEMENT(S)
else:
    STATEMENT(S)

The statements inside the else clause are executed only when the EXPRESSION evaluates to false. If an exception is raised or if the loop is terminated with the break statement, it won’t be executed.

Here is an example:

i=0
while i < 5:
    i += 1
    print('number:', i)
else:
    print('Loop completed.')
number: 1
number: 2
number: 3
number: 4
number: 5
Loop completed.

Now lew’s see what happens when you break out of the loop:

i=0
while i < 5:
    i += 1
    if i == 2:
        break
    print('number:', i)
else:
    print('Loop completed.')

The statement inside the else clause is not executed because the expression did not evaluate to false:

Number: 1

The else clause with a while loop is not often used. One common situation is when you expect to break from a loop, and if the loop continues to run until the condition evaluate to false, you can execute some statement or function.

Infinite while Loop #

An infinite loop is a loop that repeats indefinitely and never terminates until the program terminates. If the condition always evaluates to true, you get an infinite loop.

Infinite loops are generally used to make the program wait for some external event to occur. Typically, in Python, an infinite loop is created with while True: Instead of True, you can also use any other expression that always returns true.

Here is an example of an infinite while loop that will continue to prompt you to enter “Yes”:

while True:
    i = input('Please enter 'Yes': ')
    if i.strip() == 'Yes':
        break

The while loop above will run until you enter “Yes”:

Please enter 'Yes': 3
Please enter 'Yes': l
Please enter 'Yes': lin
Please enter 'Yes': No
Please enter 'Yes': Yes

Another way to terminate an infinite loop is to press CTRL+C.

When writing infinite loops, make sure you use the break statement to exit the loop at some point.

Conclusion #

The while loop repeatedly executes its statements as long the given condition evaluates to true.

If you have any questions or feedback, feel free to leave a comment.

[ad_2]

Source link

Related Posts

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.