Python while not error

In this tutorial, you'll learn about indefinite iteration using the Python while loop. You’ll be able to construct basic and complex while loops, interrupt loop execution with break and continue, use the else clause with a while loop, and deal with infinite loops.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Mastering While Loops

Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop.

In programming, there are two types of iteration, indefinite and definite:

  • With indefinite iteration, the number of times the loop is executed isn’t specified explicitly in advance. Rather, the designated block is executed repeatedly as long as some condition is met.

  • With definite iteration, the number of times the designated block will be executed is specified explicitly at the time the loop starts.

In this tutorial, you’ll:

  • Learn about the while loop, the Python control structure used for indefinite iteration
  • See how to break out of a loop or loop iteration prematurely
  • Explore infinite loops

When you’re finished, you should have a good grasp of how to use indefinite iteration in Python.

The while Loop

Let’s see how Python’s while statement is used to construct loops. We’ll start simple and embellish as we go.

The format of a rudimentary while loop is shown below:

while <expr>:
    <statement(s)>

<statement(s)> represents the block to be repeatedly executed, often referred to as the body of the loop. This is denoted with indentation, just as in an if statement.

The controlling expression, <expr>, typically involves one or more variables that are initialized prior to starting the loop and then modified somewhere in the loop body.

When a while loop is encountered, <expr> is first evaluated in Boolean context. If it is true, the loop body is executed. Then <expr> is checked again, and if still true, the body is executed again. This continues until <expr> becomes false, at which point program execution proceeds to the first statement beyond the loop body.

Consider this loop:

>>>

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100

Here’s what’s happening in this example:

  • n is initially 5. The expression in the while statement header on line 2 is n > 0, which is true, so the loop body executes. Inside the loop body on line 3, n is decremented by 1 to 4, and then printed.

  • When the body of the loop has finished, program execution returns to the top of the loop at line 2, and the expression is evaluated again. It is still true, so the body executes again, and 3 is printed.

  • This continues until n becomes 0. At that point, when the expression is tested, it is false, and the loop terminates. Execution would resume at the first statement following the loop body, but there isn’t one in this case.

Note that the controlling expression of the while loop is tested first, before anything else happens. If it’s false to start with, the loop body will never be executed at all:

>>>

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...

In the example above, when the loop is encountered, n is 0. The controlling expression n > 0 is already false, so the loop body never executes.

Here’s another while loop involving a list, rather than a numeric comparison:

>>>

>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo

When a list is evaluated in Boolean context, it is truthy if it has elements in it and falsy if it is empty. In this example, a is true as long as it has elements in it. Once all the items have been removed with the .pop() method and the list is empty, a is false, and the loop terminates.

The Python break and continue Statements

In each example you have seen so far, the entire body of the while loop is executed on each iteration. Python provides two keywords that terminate a loop iteration prematurely:

  • The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body.

  • The Python continue statement immediately terminates the current loop iteration. Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop will execute again or terminate.

The distinction between break and continue is demonstrated in the following diagram:

Python while loops: break and continue statements

break and continue

Here’s a script file called break.py that demonstrates the break statement:

 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        break
 6    print(n)
 7print('Loop ended.')

Running break.py from a command-line interpreter produces the following output:

C:UsersjohnDocuments>python break.py
4
3
Loop ended.

When n becomes 2, the break statement is executed. The loop is terminated completely, and program execution jumps to the print() statement on line 7.

The next script, continue.py, is identical except for a continue statement in place of the break:

 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        continue
 6    print(n)
 7print('Loop ended.')

The output of continue.py looks like this:

C:UsersjohnDocuments>python continue.py
4
3
1
0
Loop ended.

This time, when n is 2, the continue statement causes termination of that iteration. Thus, 2 isn’t printed. Execution returns to the top of the loop, the condition is re-evaluated, and it is still true. The loop resumes, terminating when n becomes 0, as previously.

The else Clause

Python allows an optional else clause at the end of a while loop. This is a unique feature of Python, not found in most other programming languages. The syntax is shown below:

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>

The <additional_statement(s)> specified in the else clause will be executed when the while loop terminates.

thought balloon

About now, you may be thinking, “How is that useful?” You could accomplish the same thing by putting those statements immediately after the while loop, without the else:

while <expr>:
    <statement(s)>
<additional_statement(s)>

What’s the difference?

In the latter case, without the else clause, <additional_statement(s)> will be executed after the while loop terminates, no matter what.

When <additional_statement(s)> are placed in an else clause, they will be executed only if the loop terminates “by exhaustion”—that is, if the loop iterates until the controlling condition becomes false. If the loop is exited by a break statement, the else clause won’t be executed.

Consider the following example:

>>>

>>> n = 5
>>> while n > 0:
...     n -= 1
...     print(n)
... else:
...     print('Loop done.')
...
4
3
2
1
0
Loop done.

In this case, the loop repeated until the condition was exhausted: n became 0, so n > 0 became false. Because the loop lived out its natural life, so to speak, the else clause was executed. Now observe the difference here:

>>>

>>> n = 5
>>> while n > 0:
...     n -= 1
...     print(n)
...     if n == 2:
...         break
... else:
...     print('Loop done.')
...
4
3
2

This loop is terminated prematurely with break, so the else clause isn’t executed.

It may seem as if the meaning of the word else doesn’t quite fit the while loop as well as it does the if statement. Guido van Rossum, the creator of Python, has actually said that, if he had it to do over again, he’d leave the while loop’s else clause out of the language.

One of the following interpretations might help to make it more intuitive:

  • Think of the header of the loop (while n > 0) as an if statement (if n > 0) that gets executed over and over, with the else clause finally being executed when the condition becomes false.

  • Think of else as though it were nobreak, in that the block that follows gets executed if there wasn’t a break.

If you don’t find either of these interpretations helpful, then feel free to ignore them.

When might an else clause on a while loop be useful? One common situation is if you are searching a list for a specific item. You can use break to exit the loop if the item is found, and the else clause can contain code that is meant to be executed if the item isn’t found:

>>>

>>> a = ['foo', 'bar', 'baz', 'qux']
>>> s = 'corge'

>>> i = 0
>>> while i < len(a):
...     if a[i] == s:
...         # Processing for item found
...         break
...     i += 1
... else:
...     # Processing for item not found
...     print(s, 'not found in list.')
...
corge not found in list.

An else clause with a while loop is a bit of an oddity, not often seen. But don’t shy away from it if you find a situation in which you feel it adds clarity to your code!

Infinite Loops

Suppose you write a while loop that theoretically never ends. Sounds weird, right?

Consider this example:

>>>

>>> while True:
...     print('foo')
...
foo
foo
foo
  .
  .
  .
foo
foo
foo
KeyboardInterrupt
Traceback (most recent call last):
  File "<pyshell#2>", line 2, in <module>
    print('foo')

This code was terminated by Ctrl+C, which generates an interrupt from the keyboard. Otherwise, it would have gone on unendingly. Many foo output lines have been removed and replaced by the vertical ellipsis in the output shown.

Clearly, True will never be false, or we’re all in very big trouble. Thus, while True: initiates an infinite loop that will theoretically run forever.

Maybe that doesn’t sound like something you’d want to do, but this pattern is actually quite common. For example, you might write code for a service that starts up and runs forever accepting service requests. “Forever” in this context means until you shut it down, or until the heat death of the universe, whichever comes first.

More prosaically, remember that loops can be broken out of with the break statement. It may be more straightforward to terminate a loop based on conditions recognized within the loop body, rather than on a condition evaluated at the top.

Here’s another variant of the loop shown above that successively removes items from a list using .pop() until it is empty:

>>>

>>> a = ['foo', 'bar', 'baz']
>>> while True:
...     if not a:
...         break
...     print(a.pop(-1))
...
baz
bar
foo

When a becomes empty, not a becomes true, and the break statement exits the loop.

You can also specify multiple break statements in a loop:

while True:
    if <expr1>:  # One condition for loop termination
        break
    ...
    if <expr2>:  # Another termination condition
        break
    ...
    if <expr3>:  # Yet another
        break

In cases like this, where there are multiple reasons to end the loop, it is often cleaner to break out from several different locations, rather than try to specify all the termination conditions in the loop header.

Infinite loops can be very useful. Just remember that you must ensure the loop gets broken out of at some point, so it doesn’t truly become infinite.

Nested while Loops

In general, Python control structures can be nested within one another. For example, if/elif/else conditional statements can be nested:

if age < 18:
    if gender == 'M':
        print('son')
    else:
        print('daughter')
elif age >= 18 and age < 65:
    if gender == 'M':
        print('father')
    else:
        print('mother')
else:
    if gender == 'M':
        print('grandfather')
    else:
        print('grandmother')

Similarly, a while loop can be contained within another while loop, as shown here:

>>>

>>> a = ['foo', 'bar']
>>> while len(a):
...     print(a.pop(0))
...     b = ['baz', 'qux']
...     while len(b):
...         print('>', b.pop(0))
...
foo
> baz
> qux
bar
> baz
> qux

A break or continue statement found within nested loops applies to the nearest enclosing loop:

while <expr1>:
    statement
    statement

    while <expr2>:
        statement
        statement
        break  # Applies to while <expr2>: loop

    break  # Applies to while <expr1>: loop

Additionally, while loops can be nested inside if/elif/else statements, and vice versa:

if <expr>:
    statement
    while <expr>:
        statement
        statement
else:
    while <expr>:
        statement
        statement
    statement
while <expr>:
    if <expr>:
        statement
    elif <expr>:
        statement
    else:
        statement

    if <expr>:
        statement

In fact, all the Python control structures can be intermingled with one another to whatever extent you need. That is as it should be. Imagine how frustrating it would be if there were unexpected restrictions like “A while loop can’t be contained within an if statement” or “while loops can only be nested inside one another at most four deep.” You’d have a very difficult time remembering them all.

Seemingly arbitrary numeric or logical limitations are considered a sign of poor program language design. Happily, you won’t find many in Python.

One-Line while Loops

As with an if statement, a while loop can be specified on one line. If there are multiple statements in the block that makes up the loop body, they can be separated by semicolons (;):

>>>

>>> n = 5
>>> while n > 0: n -= 1; print(n)

4
3
2
1
0

This only works with simple statements though. You can’t combine two compound statements into one line. Thus, you can specify a while loop all on one line as above, and you write an if statement on one line:

>>>

>>> if True: print('foo')

foo

But you can’t do this:

>>>

>>> while n > 0: n -= 1; if True: print('foo')
SyntaxError: invalid syntax

Remember that PEP 8 discourages multiple statements on one line. So you probably shouldn’t be doing any of this very often anyhow.

Conclusion

In this tutorial, you learned about indefinite iteration using the Python while loop. You’re now able to:

  • Construct basic and complex while loops
  • Interrupt loop execution with break and continue
  • Use the else clause with a while loop
  • Deal with infinite loops

You should now have a good grasp of how to execute a piece of code repetitively.

The next tutorial in this series covers definite iteration with for loops—recurrent execution where the number of repetitions is specified explicitly.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Mastering While Loops

В прошлой статье мы изучали цикл for – он
используется в тех случаях, когда заранее известно количество итераций,
совершаемых в цикле. Число исполнений цикла for определяется функцией range() или размером коллекции. Если диапазон значений не
известен заранее, необходимо использовать другой цикл – while: он выполняется, пока не наступит
определенное событие (или не выполнится необходимое условие). По этой причине
цикл while называют условным. Вот пример простейшего цикла while – он выполняется, пока пользователь
не введет 0:

        n = int(input())
while n != 0:
    print(n + 5)
    n = int(input())

    

Цикл while также часто называют бесконечным, поскольку он может
выполняться до тех пор, пока пользователь не остановит его нажатием
определенной клавиши. Бесконечные циклы можно создавать намеренно – для
выполнения фонового скрипта, игры, прикладной программы. Но иногда цикл while может
стать бесконечным из-за ошибки. Например, если в приведенном выше коде не
указать ввод новой переменной n = int(input()) в теле цикла, while будет
бесконечно выводить одно и то же значение, пока пользователь не остановит выполнение программы нажатием Ctrl + C.

Управление бесконечным циклом while в Питоне

Самый простой способ управления бесконечным циклом –
использование оператора break.
В приведенном ниже коде список lst генерируется случайным образом, и до начала цикла его длина
неизвестна. Однако выполнение цикла можно оставить, как только список опустеет
в результате многократного выполнения операции pop():

        import random
lst = [i for i in range(random.randint(5, 500))]
while True:
    if not lst:
        break
    print(lst.pop())

    

Если выполнение цикла не остановить сразу же, как только список опустеет, появится ошибка:

        IndexError: pop from empty list
    

Оператор break также помогает сократить количество итераций и прекратить выполнение программы, как только нужное решение найдено. Например, таким образом можно найти наименьший делитель числа n, отличный от 1:

        n = int(input())
i = 2
while True:
    if n % i == 0:
        break
    i += 1
print(i)

    

Помимо break,
управлять бесконечным циклом можно с помощью флагов (сигнальных меток). В
приведенном ниже примере программа бесконечно запрашивает у пользователя ввод
любого слова, пока пользователь не введет exit. Это событие меняет статус цикла на False, и работа программы завершается:

        text = 'Введите любое слово: '
text += 'nИли введите exit для выхода: '

active = True
while active:
    message = input(text)
    if message == 'exit':
        active = False
    else: 
        print(message)

    

Пропуск итераций в цикле while

Оператор continue
можно использовать для пропуска операций, если элементы не соответствуют
заданным критериям. Этот код работает, пока не будет сформирован список из 5
элементов – при этом в список не включаются числа в диапазоне между 90 и 120, а
также число 50:

        sp = []
while len(sp) < 5:
    num = int(input())
    if num == 50 or 90 <= num <= 120:
        continue
    sp.append(num)  
print(sp)

    

Если пользователь введет набор цифр 45 50 121 119
95 105 3 4 7
, в список будут добавлены только числа, соответствующие
критериям:

        [45, 121, 3, 4, 7]
    

Особенности цикла while

1. В цикле while можно использовать опциональный параметр else. В этом примере процедура pop() выполняется, пока
список не опустеет, после чего выводится сообщение Список пуст:

        import random
lst = [i for i in range(random.randint(5, 500))]
while len(lst) > 1:
    print(lst.pop())
else:
    print('Список пуст')

    

2. В цикле while можно использовать любое количество условий и условных
операторов and, or, иnot:

        n = int(input())
while True:
    if n == 0:
        break
    elif n > 50 or n <= -50:
        break
    elif n % 2 == 0:
        break
    print(n / 5)
    n = int(input())

    

3. Цикл while может быть вложенным. Этот код выводит простые числа из
диапазона от 2 до 100:

        i = 2
while(i < 100):
   j = 2
   while j <= i / j:
      if not i % j:
          break
      j = j + 1
   if j > i / j:
       print(f'{i} - простое число')
   i = i + 1

    

4. В качестве вложенных циклов while могут включать в себя циклы for. Этот код, к примеру,
будет бесконечно печатать цифры в диапазоне от 0 до 5:

        while True:
    for i in range(5):
        print(i)

    

5. Любой цикл for можно заменить циклом while, но обратное возможно только в том случае, когда количество итераций можно определить до начала цикла. К примеру, эти циклы while и for равнозначны – оба печатают цифры от 0 до 9:

        i = 0
while i < 10:
    print(i)
    i += 1

for i in range(10):
    print(i)

    

А этот цикл while заменить циклом for невозможно – программа будет бесконечно
возводить в квадрат все введенные пользователем числа, пока не получит 0:

        n = int(input())
while True:
    if n == 0:
        break
    print(n ** 2)
    n = int(input())

    

Практика

Задание 1

Напишите программу, которая принимает на вход целые числа и
вычисляет их сумму, пока пользователь не введет 0.

Пример ввода:

        4
5
6
0

    

Вывод:

        15
    

Решение:

        summa = 0
while True:
    n = int(input())
    summa += n
    if n == 0:
        break
print(summa)

    

Задание 2

Напишите программу, которая получает от пользователя число n > 100, и вычисляет (без
использования методов строк) произведение цифр, из которых n состоит.

Пример ввода:

        335
    

Вывод:

        45
    

Решение:

        n = int(input())
prod = 1

while n:
    prod *= n % 10
    n //= 10
print(prod)

    

Задание 3

Напишите программу, которая получает на вход два числа a и b, и находит наименьшее число c, которое без остатка
делится на a и b.

Пример ввода:

        7
12
    

Вывод:

        84
    

Решение:

        a, b = int(input()), int(input())
c = a
while c % b:
    c += a
print(c)

    

Задание 4

Напишите программу, которая составляет строку из полученных
от пользователя слов, пока длина строки не достигнет 50 символов. Слова,
начинающиеся с гласных, в строку не включаются.

Пример ввода:

        о
бойся
Бармаглота
сын
он
так
свиреп
и
дик
а
в глуще
рымит

    

Вывод:

        бойся Бармаглота сын так свиреп дик в глуще рымит
    

Решение:

        st = ''
while len(st) < 50:
    word = input()
    if word[0] in 'аиеёоуыэюя':
        continue
    st += ' ' + word
print(st)

    

Задание 5

Напишите программу для конвертации числа из десятичного системы
в двоичную без использования функции bin().

Пример ввода:

        25
    

Вывод:

        11001
    

Решение:

        n = int(input())
result = ''
while n > 0:
    result = str(n % 2) + result
    n = n // 2
print(result)

    

Задание 6

Напишите программу, которая получает на вход число и без
использования строковых методов переставляет цифры в обратном порядке.

Пример ввода:

        176435
    

Вывод:

        534671
    

Решение:

        n = int(input())
rev = 0
while n!= 0:
    r = n % 10
    rev = rev * 10 + r
    n = n // 10
print(rev)

    

Задание 7

Напишите программу для вычисления факториала числа n без использования функции math.factorial().

Пример ввода:

        7
    

Вывод:

        5040
    

Решение:

        n = int(input())
fact = 1

while n > 1:
    fact *= n 
    n -= 1
print(fact)

    

Задание 8

Напишите программу, которая получает от пользователя число n и
определяет, является ли оно простым, или у него есть делители, кроме 1 и самого
себя.

Пример ввода:

        60
    

Вывод:

        60 делится на 2
60 делится на 3
60 делится на 4
60 делится на 5
60 делится на 6
60 делится на 10
60 делится на 12
60 делится на 15
60 делится на 20
60 делится на 30
Таким образом, 60 не является простым числом

    

Решение:

        n = int(input())
flag = False
i = 2
while i < n:
    if n % i ==0:
        flag = True
        print(f'{n} делится на {i}')
    i += 1   
if flag:
    print(f'Таким образом, {n} не является простым числом')
else:
    print(f'{n} - простое число')

    

Задание 9

Напишите программу, использующую вложенный цикл while для вывода треугольника
размером n x n х n, состоящего из символов*.

Пример ввода:

        6
    

Вывод:

        *
**
***
****
*****
******

    

Решение:

        n = int(input())
i, j = 0, 0
while i < n:
    while j <= i:
        print('*', end='')
        j += 1
    j = 0
    i += 1
    print('')

    

Задание 10

Напишите программу для запоминания английских названий месяцев:

1. Русские названия месяцев выводятся в случайном порядке с
помощью метода random.shuffle().

2. Пользователь получает три попытки для написания правильного
названия на английском.

3. После трех неверных попыток программа переходит к другому
слову.

Пример ввода:

        Месяц март по-английски называется: march
Месяц январь по-английски называется: January
Месяц август по-английски называется: august
Месяц май по-английски называется: may
Месяц апрель по-английски называется: aprile
Неверно! Осталось попыток: 2
Месяц апрель по-английски называется: aprill
Неверно! Осталось попыток: 1
Месяц апрель по-английски называется: appril
Неверно! Осталось попыток: 0
Попытки исчерпаны!
Месяц июль по-английски называется: july
Месяц сентябрь по-английски называется: september
Месяц июнь по-английски называется: june
Месяц октябрь по-английски называется: october
Месяц ноябрь по-английски называется: november
Месяц декабрь по-английски называется: december
Месяц февраль по-английски называется: february

    

Вывод:

        Конец игры
Количество правильных ответов: 11
Число ошибок: 3

    

Решение:

        import random
correct, wrong, attempts = 0, 0, 3
months = {'январь': 'January', 'февраль': 'February', 'март': 'March',
          'апрель': 'April', 'май': 'May', 'июнь': 'June',
           'июль': 'July', 'август': 'August', 'сентябрь': 'September',
          'октябрь': 'October', 'ноябрь': 'November', 'декабрь': 'December'}
rand_keys = list(months.keys())
random.shuffle(rand_keys)
for key in rand_keys:
    counter = 0
    while counter < attempts:
        spelling = input(f'Месяц {key} по-английски называется: ')
        if spelling.title() == months[key]:
            correct += 1
            break
        else:
            counter += 1
            wrong += 1
            print(f'Неверно! Осталось попыток: {attempts - counter}')
    else:
        print(f'Попытки исчерпаны!')
        
print('Конец игры')
print(f'Количество правильных ответов: {correct}')
print(f'Число ошибок: {wrong}')

    

Подведем итоги

Цикл while используют в случаях, когда число итераций невозможно
оценить заранее. Во всех остальных случаях лучше применять цикл for. Чтобы цикл while случайно
не превратился в бесконечный, стоит продумать все события и условия, которые
должны приводить к своевременному прерыванию программы.

В следующей статье приступим к изучению функций.

***

Содержание самоучителя

  1. Особенности, сферы применения, установка, онлайн IDE
  2. Все, что нужно для изучения Python с нуля – книги, сайты, каналы и курсы
  3. Типы данных: преобразование и базовые операции
  4. Методы работы со строками
  5. Методы работы со списками и списковыми включениями
  6. Методы работы со словарями и генераторами словарей
  7. Методы работы с кортежами
  8. Методы работы со множествами
  9. Особенности цикла for
  10. Условный цикл while
  11. Функции с позиционными и именованными аргументами
  12. Анонимные функции
  13. Рекурсивные функции
  14. Функции высшего порядка, замыкания и декораторы
  15. Методы работы с файлами и файловой системой

Содержание:развернуть

  • Немного информатики
  • Синтаксис цикла while
  • Несколько примеров использования цикла while
  • break и continue
  • else
  • while true или бесконечный цикл
  • Best practice
  • Цикл while в одну строку

  • Вложенные циклы

  • Как выйти с помощью break из двух циклов

Использование циклов предоставляет программисту возможность многократного исполнения определенного участка кода. Это один из основных рабочих инструментов любого разработчика, и практически ни одна из существующих программ не обходится без него.

Циклы в языке Python представлены двумя основными конструкциями: while и for. Цикл while считается универсальным, в то время как for нужен для обхода последовательности поэлементно. Более подробную информацию о цикле for вы можете прочитать здесь.

Так или иначе, обе конструкции одинаково применимы и являются важнейшими элементами любого высокоуровневого языка, в том числе и языка Python.

Немного информатики

Как было отмечено выше,

Цикл — это управляющая конструкция, которая раз за разом выполняет серию команд (тело цикла) до тех пор, пока условие для выполнения является истинным.

Напишем на псевдокоде классическую схему:

повторять, пока условие
начало цикла
последовательность инструкций
конец цикла

Конструкция начинает свою работу с проверки условия, и, если оно истинно, запускается цикл. На каждой новой итерации (единичный проход по циклу) условие продолжения проверяется вновь. Таким образом, последовательность инструкций будет исполняться до тех пор, пока это условие, наконец, не окажется ложным.

Циклы, как механизм программирования, нужны, главным образом, для упрощения написания кода. Вполне очевидно, что создавать программу, выполняющую определённую операцию для каждой точки 4К дисплея в отсутствии циклов — это вручную повторять описание нужной команды 4096*2160 раз. 🤔 Много? Безусловно.

Применение в этой задаче всего одного цикла позволит сократить длину кода, как минимум, на 6 порядков. А если представить, что ту же самую программу нужно переписать для 8К монитора, то, вместо изменения всего одной инструкции в счетчике цикла, вам придётся дописывать ещё пару десятков миллионов строк кода, что является попросту недопустимым по своей величине и трудозатратам объёмом.

Польза циклов ясна и очевидна. Обладая мощной выразительностью и ёмкой натурой, они, без сомнений, являются одним из фундаментальных конструктов высокоуровневого программирования. Каждому разработчику необходимо знать и понимать принципы их работы.

Синтаксис цикла while

В самом простом случае, цикл while в python очень похож по своей структуре на условную конструкцию с if:

import time
a = 1

if a == 1:
print("I'm the condition")

while a == 1:
print("I'm the loop")
time.sleep(1)

И в том и в другом случае, блок кода внутри (инструкция print(‘…’)) будет исполнен тогда и только тогда, когда условие (a == 1) будет иметь значение True. Вот только в конструкции с if, при успешной проверке, вывод на экран будет выполнен всего один раз, а в случае с while фраза «I’m the loop» будет печататься бесконечно.

Такое явление называется бесконечным циклом. У них есть свои определенные смысл и польза, но их мы разберём чуть позже, поскольку чаще всего цикл всё-таки должен как-то заканчиваться. И вполне логично, что для его завершения нужно произвести определенные манипуляции с условием.

Переменная a, в примере выше, называется управляющей (или счетчик). При помощи таких переменных можно контролировать момент выхода из цикла. Для этого их следует сравнить с каким-либо значением.

count = 1 # фиксируем начальное значение
while count <= 10: # и конечное (включительно)
print(count, end=' ')
count += 1

# после 9-й итерации в count будет храниться значение 10
# это удовлетворяет условию count <= 10, поэтому на 10-м витке будет выведено число 10
# (как видно, значение счетчика печатается до его инкрементирования)
# после count станет равным 11, а, значит, следующий прогон цикла не состоится, и он будет прерван
# в итоге получаем:
> 1 2 3 4 5 6 7 8 9 10

В Python есть и более сложные, составные условия. Они могут быть сколь угодно длинными, а в их записи используются логические операторы (not, and, or):

dayoff = False
sunrise = 6
sunset = 18

worktime = 12

# пример составного условия
while not dayoff and sunrise <= worktime <= sunset:
if sunset == worktime:
print("Finally it's over!")
else:
print('You have ', sunset - worktime, ' hours to work')
worktime += 1

>
You have 6 hours to work
You have 5 hours to work
You have 4 hours to work
You have 3 hours to work
You have 2 hours to work
You have 1 hours to work
Finally it's over!

Как можно заметить, управляющая переменная вовсе не обязана являться счётчиком. Она может быть просто логической переменной, чье значение изменяется где-то в самом цикле:

num = 0
control = True
while num < 10:
num += 1

# аналогичная запись
num = 0
control = True
while control:
if num == 10:
control = False
num += 1

Стоит иметь в виду, что использование неинициализированной переменной в качестве управляющей цикла обязательно приведёт к возникновению ошибки:

# unknown до этого нигде не была объявлена
while unknown:
print('+')

>
Traceback (most recent call last):
while unknown:
NameError: name 'unknown' is not defined

Несколько примеров использования цикла while

Идея циклов while проста — требуется определенное количество раз сделать что-то? Заведи счётчик и уменьшай/увеличивай его в теле цикла.

x = 20
y = 30
while x < y:
print(x, end=' ')
x = x + 3

> 20 23 26 29

Своеобразным счётчиком может быть даже строка:

word = "pythonchik"
while word:
print(word, end=" ")
# на каждой итерации убираем символ с конца
word = word[:-1]

> pythonchik pythonchi pythonch pythonc python pytho pyth pyt py p

break и continue

Оператор break заставляет интерпретатор прервать выполнение цикла и перейти к следующей за ним инструкции:

counter = 0
while True:
if counter == 10:
break
counter += 1

Цикл прервётся после того, как значение счетчика дойдёт до десяти.

Существует похожий оператор под названием continue, однако он не прекращает выполнение всей конструкции, а прерывает лишь текущую итерацию, переходя затем в начало цикла:

# классический пример вывода одних лишь чётных значений
z = 10
while z:
z -= 1
if z % 2 != 0:
continue
print(z, end=" ")

> 8 6 4 2 0

Эти операторы бывают весьма удобны, однако плохой практикой считается написание кода, который чересчур ими перегружен.

else

В Python-циклах часть else выполняется лишь тогда, когда цикл отработал, не будучи прерван break-ом.

В реальной практике, else в циклах применяется нечасто. Такая конструкция отлично сработает, когда будет необходимо проверить факт выполнения всех итераций цикла.

👉 Пример из практики: проверка доступности всех выбранных узлов сети

Например, обойти все узлы локальной сети и

def print_prime_list(list_of_numbers: list) -> None:
""" функция выведет список чисел,
если каждое из этих чисел является простым """
number_count = len(list_of_numbers) # количество чисел

i = 0
while i < number_count:
x = list_of_numbers[i] // 2
if x != 0 and list_of_numbers[i] % x == 0:
break
i += 1
else:
print(f'{list_of_numbers} - list is prime!')

print_prime_list([11, 100, 199]) # 100 - не простое число
>

print_prime_list([11, 113, 199])
> [11, 113, 199]

В каком-либо другом языке стоило бы завести булеву переменную, в которой хранится результат проверки, но у Python, как всегда, есть способ получше!

while true или бесконечный цикл

В большинстве случаев, бесконечные циклы появляются из-за логических ошибок программиста (например, когда условие цикла while при любых вариантах равно True). Поэтому следует внимательно следить за условием, при котором цикл будет завершаться.

Однако вы некоторых случая бесконечный цикл делают намерено:

  1. Если нужно производить какие-то действия с интервалом, и выходить из цикла лишь в том случае, когда внутри тела «зашито» условие выхода.
    Пример: функция, которая возвращает connection базы данных. Если связь с базой данных отсутствует, соединение будет пытаться (в цикле) установиться до тех пор, пока не установится.
  2. Если вы пишете полноценный демон, который продолжительное время висит как процесс в системе и периодически производит какие-то действия. В таком случае остановкой цикла будет прерывание работы программы. Пример: скрипт, который раз в 10 минут «пингует» IP адреса и пишет в лог отчет о доступности этих адресов.

💁‍♂️ Совет: в бесконечных циклах рекомендуется ставить таймаут выполнения после каждой итерации, иначе вы очень сильно нагрузите CPU:

import time

while True:
print("Бесконечный цикл")
time.sleep(1)

>
Бесконечный цикл
Бесконечный цикл
Бесконечный цикл
Traceback (most recent call last):
File "main.py", line 5, in <module>
time.sleep(1)
KeyboardInterrupt

Aborted!

Код был прерван комбинацией клавиш ^Ctrl + C. Иначе цикл продолжался бы бесконечно.

Best practice

Цикл while в одну строку

Для составных конструкций (таких, где нужен блок с отступом), можно этот отступ убрать, но только если в блоке используются простые операторы. Отделяются они всё также двоеточием.

Например, записи:

while x < y:
x +=1

# и

while x < y: x += 1

будут считаться эквивалентными, и при чтении второй из них интерпретатор не будет выдавать ошибку.

Вложенные циклы

Вложенные while циклы встречаются не так часто, как их братья (или сестры) for, что, однако не мешает им быть полезными. Простой пример — выведем на экран таблицу умножения:

q = 1
while q <= 9:
w = 1
while w <= 9:
print(q * w, end=" ")
w += 1
q += 1
print("")

>
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81

Нет никаких проблем с использованием вложенных циклов while, однако стоит иметь в виду, что вложения свыше третьего уровня будут уже практически нечитаемыми для человека.

Как выйти с помощью break из двух циклов

В случае вложенных циклов, оператор break завершает работу только того цикла, внутри которого он был вызван:

i = 100
j = 200
while i < 105:
while j < 205:
if j == 203:
break
print('J', j)
j += 1
print('I', i)
i += 1

>
J 200
J 201
J 202
# здесь видно, что внутренний цикл прерывается, но внешний продолжает работу
I 100
I 101
I 102
I 103
I 104

В Python не существует конструкций, которая прерывала бы сразу несколько циклов. Но есть как минимум 3 способа, которыми можно реализовать данное поведение:

Способ №1
Используем конструкцию for ... else ...:

def same_values_exists(list_1: list, list_2: list) -> None:
""" функция выводит на экран
первые совпавшие числа из списков """
for i in list_1:
for j in list_2:
print("compare: ", i, j)
if i == j:
print(f"found {i}")
break
else:
continue
break

same_values_exists([0, 10, -2, 23], [-2, 2])
>
compare: 0 -2
compare: 0 2
compare: 10 -2
compare: 10 2
compare: -2 -2
found -2

Если все итерации вложенного цикла сработают, выполнится else, который скажет внешнему циклу продолжить выполнение. Если во внутреннем цикле сработает break, сразу выполнится второй break.

Способ №2
Через создание дополнительного флага:

def same_values_exists(list_1: list, list_2: list) -> None:
""" функция выводит на экран
первые совпавшие числа из списков """
break_the_loop = False

for i in list_1:
for j in list_2:
print("compare: ", i, j)
if i == j:
print(f"found {i}")
break_the_loop = True
break
if break_the_loop:
break

same_values_exists([0, 10, -2, 23], [-2, 2])
>
compare: 0 -2
compare: 0 2
compare: 10 -2
compare: 10 2
compare: -2 -2
found -2

Внешний цикл был прерван вслед за внутренним. Дело сделано!

Способ №3
Если циклы находятся в функции (как в нашем примере), достаточно просто сделать
return:

def same_values_exists(list_1: list, list_2: list) -> None:
""" функция выводит на экран
первые совпавшие числа из списков """
for i in list_1:
for j in list_2:
print("compare: ", i, j)
if i == j:
print(f"found {i}")
return

same_values_exists([0, 10, -2, 23], [-2, 2])

>
compare: 0 -2
compare: 0 2
compare: 10 -2
compare: 10 2
compare: -2 -2
found -2

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops

Welcome! If you want to learn how to work with while loops in Python, then this article is for you.

While loops are very powerful programming structures that you can use in your programs to repeat a sequence of statements.

In this article, you will learn:

  • What while loops are.
  • What they are used for.
  • When they should be used.
  • How they work behind the scenes.
  • How to write a while loop in Python.
  • What infinite loops are and how to interrupt them.
  • What while True is used for and its general syntax.
  • How to use a break statement to stop a while loop.

You will learn how while loops work behind the scenes with examples, tables, and diagrams.

Are you ready? Let’s begin. 🔅

🔹 Purpose and Use Cases for While Loops

Let’s start with the purpose of while loops. What are they used for?

They are used to repeat a sequence of statements an unknown number of times. This type of loop runs while a given condition is True and it only stops when the condition becomes False.

When we write a while loop, we don’t explicitly define how many iterations will be completed, we only write the condition that has to be True to continue the process and False to stop it.

💡 Tip: if the while loop condition never evaluates to False, then we will have an infinite loop, which is a loop that never stops (in theory) without external intervention.

These are some examples of real use cases of while loops:

  • User Input: When we ask for user input, we need to check if the value entered is valid. We can’t possibly know in advance how many times the user will enter an invalid input before the program can continue. Therefore, a while loop would be perfect for this scenario.
  • Search: searching for an element in a data structure is another perfect use case for a while loop because we can’t know in advance how many iterations will be needed to find the target value. For example, the Binary Search algorithm can be implemented using a while loop.
  • Games: In a game, a while loop could be used to keep the main logic of the game running until the player loses or the game ends. We can’t know in advance when this will happen, so this is another perfect scenario for a while loop.

🔸 How While Loops Work

Now that you know what while loops are used for, let’s see their main logic and how they work behind the scenes. Here we have a diagram:

image-24

While Loop

Let’s break this down in more detail:

  • The process starts when a while loop is found during the execution of the program.
  • The condition is evaluated to check if it’s True or False.
  • If the condition is True, the statements that belong to the loop are executed.
  • The while loop condition is checked again.
  • If the condition evaluates to True again, the sequence of statements runs again and the process is repeated.
  • When the condition evaluates to False, the loop stops and the program continues beyond the loop.

One of the most important characteristics of while loops is that the variables used in the loop condition are not updated automatically. We have to update their values explicitly with our code to make sure that the loop will eventually stop when the condition evaluates to False.

🔹 General Syntax of While Loops

Great. Now you know how while loops work, so let’s dive into the code and see how you can write a while loop in Python. This is the basic syntax:

image-105

While Loop (Syntax)

These are the main elements (in order):

  • The while keyword (followed by a space).
  • A condition to determine if the loop will continue running or not based on its truth value (True or False ).
  • A colon (:) at the end of the first line.
  • The sequence of statements that will be repeated. This block of code is called the «body» of the loop and it has to be indented. If a statement is not indented, it will not be considered part of the loop (please see the diagram below).

image-7

💡 Tip: The Python style guide (PEP 8) recommends using 4 spaces per indentation level. Tabs should only be used to remain consistent with code that is already indented with tabs.

Now that you know how while loops work and how to write them in Python, let’s see how they work behind the scenes with some examples.

How a Basic While Loop Works

Here we have a basic while loop that prints the value of i while i is less than 8 (i < 8):

i = 4

while i < 8:
    print(i)
    i += 1

If we run the code, we see this output:

4
5
6
7

Let’s see what happens behind the scenes when the code runs:

image-16

  • Iteration 1: initially, the value of i is 4, so the condition i < 8 evaluates to True and the loop starts to run. The value of i is printed (4) and this value is incremented by 1. The loop starts again.
  • Iteration 2: now the value of i is 5, so the condition i < 8 evaluates to True. The body of the loop runs, the value of i is printed (5) and this value i is incremented by 1. The loop starts again.
  • Iterations 3 and 4: The same process is repeated for the third and fourth iterations, so the integers 6 and 7 are printed.
  • Before starting the fifth iteration, the value of i is 8. Now the while loop condition i < 8 evaluates to False and the loop stops immediately.

💡 Tip: If the while loop condition is False before starting the first iteration, the while loop will not even start running.

User Input Using a While Loop

Now let’s see an example of a while loop in a program that takes user input. We will the input() function to ask the user to enter an integer and that integer will only be appended to list if it’s even.

This is the code:

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)

The loop condition is len(nums) < 4, so the loop will run while the length of the list nums is strictly less than 4.

Let’s analyze this program line by line:

  • We start by defining an empty list and assigning it to a variable called nums.
nums = []
  • Then, we define a while loop that will run while len(nums) < 4.
while len(nums) < 4:
  • We ask for user input with the input() function and store it in the user_input variable.
user_input = int(input("Enter an integer: "))

💡 Tip: We need to convert (cast) the value entered by the user to an integer using the int() function before assigning it to the variable because the input() function returns a string (source).

  • We check if this value is even or odd.
if user_input % 2 == 0:
  • If it’s even, we append it to the nums list.
nums.append(user_input)
  • Else, if it’s odd, the loop starts again and the condition is checked to determine if the loop should continue or not.

If we run this code with custom user input, we get the following output:

Enter an integer: 3
Enter an integer: 4    
Enter an integer: 2    
Enter an integer: 1
Enter an integer: 7
Enter an integer: 6    
Enter an integer: 3
Enter an integer: 4    

This table summarizes what happens behind the scenes when the code runs:

image-86

💡 Tip: The initial value of len(nums) is 0 because the list is initially empty. The last column of the table shows the length of the list at the end of the current iteration. This value is used to check the condition before the next iteration starts.

As you can see in the table, the user enters even integers in the second, third, sixth, and eight iterations and these values are appended to the nums list.

Before a «ninth» iteration starts, the condition is checked again but now it evaluates to False because the nums list has four elements (length 4), so the loop stops.

If we check the value of the nums list when the process has been completed, we see this:

>>> nums
[4, 2, 6, 4]

Exactly what we expected, the while loop stopped when the condition len(nums) < 4 evaluated to False.

Now you know how while loops work behind the scenes and you’ve seen some practical examples, so let’s dive into a key element of while loops: the condition.

🔹 Tips for the Condition in While Loops

Before you start working with while loops, you should know that the loop condition plays a central role in the functionality and output of a while loop.

image-25

You must be very careful with the comparison operator that you choose because this is a very common source of bugs.

For example, common errors include:

  • Using < (less than) instead of <= (less than or equal to) (or vice versa).
  • Using > (greater than) instead of >= (greater than or equal to) (or vice versa).  

This can affect the number of iterations of the loop and even its output.

Let’s see an example:

If we write this while loop with the condition i < 9:

i = 6

while i < 9:
    print(i)
    i += 1

We see this output when the code runs:

6
7
8

The loop completes three iterations and it stops when i is equal to 9.

This table illustrates what happens behind the scenes when the code runs:

image-20

  • Before the first iteration of the loop, the value of i is 6, so the condition i < 9 is True and the loop starts running. The value of i is printed and then it is incremented by 1.
  • In the second iteration of the loop, the value of i is 7, so the condition i < 9 is True. The body of the loop runs, the value of i is printed, and then it is incremented by 1.
  • In the third iteration of the loop, the value of i is 8, so the condition i < 9 is True. The body of the loop runs, the value of i is printed, and then it is incremented by 1.
  • The condition is checked again before a fourth iteration starts, but now the value of i is 9, so i < 9 is False and the loop stops.

In this case, we used < as the comparison operator in the condition, but what do you think will happen if we use <= instead?

i = 6

while i <= 9:
    print(i)
    i += 1

We see this output:

6
7
8
9

The loop completes one more iteration because now we are using the «less than or equal to» operator <= , so the condition is still True when i is equal to 9.

This table illustrates what happens behind the scenes:

image-21

Four iterations are completed. The condition is checked again before starting a «fifth» iteration. At this point, the value of i is 10, so the condition i <= 9 is False and the loop stops.

🔸 Infinite While Loops

Now you know how while loops work, but what do you think will happen if the while loop condition never evaluates to False?

image-109

What are Infinite While Loops?

Remember that while loops don’t update variables automatically (we are in charge of doing that explicitly with our code). So there is no guarantee that the loop will stop unless we write the necessary code to make the condition False at some point during the execution of the loop.

If we don’t do this and the condition always evaluates to True, then we will have an infinite loop, which is a while loop that runs indefinitely (in theory).

Infinite loops are typically the result of a bug, but they can also be caused intentionally when we want to repeat a sequence of statements indefinitely until a break statement is found.

Let’s see these two types of infinite loops in the examples below.

💡 Tip: A bug is an error in the program that causes incorrect or unexpected results.

Example of Infinite Loop

This is an example of an unintentional infinite loop caused by a bug in the program:

# Define a variable
i = 5

# Run this loop while i is less than 15
while i < 15:
    # Print a message
    print("Hello, World!")
    

Analyze this code for a moment.

Don’t you notice something missing in the body of the loop?

That’s right!

The value of the variable i is never updated (it’s always 5). Therefore, the condition i < 15 is always True and the loop never stops.

If we run this code, the output will be an «infinite» sequence of Hello, World! messages because the body of the loop print("Hello, World!") will run indefinitely.

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
.
.
.
# Continues indefinitely

To stop the program, we will need to interrupt the loop manually by pressing CTRL + C.

When we do, we will see a KeyboardInterrupt error similar to this one:

image-116

To fix this loop, we will need to update the value of i in the body of the loop to make sure that the condition i < 15 will eventually evaluate to False.

This is one possible solution, incrementing the value of i by 2 on every iteration:

i = 5

while i < 15:
    print("Hello, World!")
    # Update the value of i
    i += 2

Great. Now you know how to fix infinite loops caused by a bug. You just need to write code to guarantee that the condition will eventually evaluate to False.

Let’s start diving into intentional infinite loops and how they work.

🔹 How to Make an Infinite Loop with While True

We can generate an infinite loop intentionally using while True. In this case, the loop will run indefinitely until the process is stopped by external intervention (CTRL + C) or when a break statement is found (you will learn more about break in just a moment).

This is the basic syntax:

image-35

Instead of writing a condition after the while keyword, we just write the truth value directly to indicate that the condition will always be True.

Here we have an example:

>>> while True:
	print(0)

	
0
0
0
0
0
0
0
0
0
0
0
0
0
Traceback (most recent call last):
  File "<pyshell#2>", line 2, in <module>
    print(0)
KeyboardInterrupt

The loop runs until CTRL + C is pressed, but Python also has a break statement that we can use directly in our code to stop this type of loop.

The break statement

This statement is used to stop a loop immediately. You should think of it as a red «stop sign» that you can use in your code to have more control over the behavior of the loop.

image-110

According to the Python Documentation:

The break statement, like in C, breaks out of the innermost enclosing for or while loop.

This diagram illustrates the basic logic of the break statement:

image-111

The break statement

This is the basic logic of the break statement:

  • The while loop starts only if the condition evaluates to True.
  • If a break statement is found at any point during the execution of the loop, the loop stops immediately.
  • Else, if break is not found, the loop continues its normal execution and it stops when the condition evaluates to False.

We can use break to stop a while loop when a condition is met at a particular point of its execution, so you will typically find it within a conditional statement, like this:

while True:
    # Code
    if <condition>:
    	break
    # Code

This stops the loop immediately if the condition is True.

💡 Tip: You can (in theory) write a break statement anywhere in the body of the loop. It doesn’t necessarily have to be part of a conditional, but we commonly use it to stop the loop when a given condition is True.

Here we have an example of break in a while True loop:

image-41

Let’s see it in more detail:

The first line defines a while True loop that will run indefinitely until a break statement is found (or until it is interrupted with CTRL + C).

while True:

The second line asks for user input. This input is converted to an integer and assigned to the variable user_input.

user_input = int(input("Enter an integer: "))

The third line checks if the input is odd.

if user_input % 2 != 0:

If it is, the message This number is odd is printed and the break statement stops the loop immediately.

print("This number of odd")
break

Else, if the input is even , the message This number is even is printed and the loop starts again.

print("This number is even")

The loop will run indefinitely until an odd integer is entered because that is the only way in which the break statement will be found.

Here we have an example with custom user input:

Enter an integer: 4
This number is even
Enter an integer: 6
This number is even
Enter an integer: 8
This number is even
Enter an integer: 3
This number is odd
>>> 

🔸 In Summary

  • While loops are programming structures used to repeat a sequence of statements while a condition is True. They stop when the condition evaluates to False.
  • When you write a while loop, you need to make the necessary updates in your code to make sure that the loop will eventually stop.
  • An infinite loop is a loop that runs indefinitely and it only stops with external intervention or when a break statement is found.
  • You can stop an infinite loop with CTRL + C.
  • You can generate an infinite loop intentionally with while True.
  • The break statement can be used to stop a while loop immediately.

I really hope you liked my article and found it helpful. Now you know how to work with While Loops in Python.

Follow me on Twitter @EstefaniaCassN and if you want to learn more about this topic, check out my online course Python Loops and Looping Techniques: Beginner to Advanced.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Python while loop is used to repeat a block of code until the specified condition is False.
  • The while loop is used when we don’t know the number of times the code block has to execute.
  • We should take proper care in writing while loop condition if the condition never returns False, the while loop will go into the infinite loop.
  • Every object in Python has a boolean value. If the value is 0 or None, then the boolean value is False. Otherwise, the boolean value is True.
  • We can define an object boolean value by implementing __bool__() function.
  • We use the reserved keyword – while – to implement the while loop in Python.
  • We can terminate the while loop using the break statement.
  • We can use continue statement inside while loop to skip the code block execution.
  • Python supports nested while loops.

Python while Loop Syntax

while condition:
    # while block code

Flow Diagram of while Loop

Flow Chart While Loop
while Loop Flow Diagram

Python while Loop Examples

Let’s say we have to print a message given number of times. We can use while loop to write this utility function.

def print_msg(count, msg):
    while count > 0:
        print(msg)
        count -= 1


print_msg(3, "Hello World")

Output:

Python While Loop Example
Python while Loop Example

while Loop with break Statement

Sometimes we explicitly want to execute a code block indefinitely until the exit signal is received. We can implement this feature using “while True” block and break statement.

Here is an example of a utility script that takes the user input (integer) and prints its square value. The program terminates when the user enters 0.

while True:
    i = input('Please enter an integer (0 to exit):n')
    i = int(i)
    if i == 0:
        print("Exiting the Program")
        break
    print(f'{i} square is {i ** 2}')

Here is the output of a sample run of this program.

While Loop Break Statement
Python while Loop with break Statement

Python while Loop with continue Statement

Let’s say we want the above script to work with positive numbers only. In that case, we can use continue statement to skip the execution when user enters a negative number.

while True:
    i = input('Please enter an integer (0 to exit):n')
    i = int(i)
    if i < 0:
        print("The program works with Positive Integers only.")
        continue
    if i == 0:
        print("Exiting the Program")
        break
    print(f'{i} square is {i ** 2}')

Output:

Please enter an integer (0 to exit):
5
5 square is 25
Please enter an integer (0 to exit):
-10
The program works with Positive Integers only.
Please enter an integer (0 to exit):
0
Exiting the Program

Python while Loop with else Statement

We can use else block with the while loop. The else block code gets executed when the while loop terminates normally i.e. the condition becomes False.

If the while loop terminates because of Error or break statement, the else block code is not executed.

count = 5

while count > 0:
    print("Welcome")
    count -= 1
else:
    print("Exiting the while Loop")

Output:

Python While Loop With Else Block
Python While Loop With Else Block

Let’s see what happens when the while loop terminates because of an error.

count = 5

while count > 0:
    print("Welcome")
    count -= 1
    if count == 2:
        raise ValueError
else:
    print("Exiting the while Loop")

Output:

Welcome
Welcome
Welcome
Traceback (most recent call last):
  File "/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/while-loop.py", line 7, in <module>
    raise ValueError
ValueError
While Loop Else With Error
While Loop Else with Error

Let’s change the program to break out of the while loop.

count = 5

while count > 0:
    print("Welcome")
    count -= 1
    if count == 2:
        break
else:
    print("Exiting the while Loop")

Output:


Nested while Loop Example

We can also have nested while loops. Here is an example of generating a list of tuples using nested while loops.

i = 3
j = 3

list_tuples = []
while i > 0:
    while j > 0:
        t = (i, j)
        list_tuples.append(t)
        j -= 1
    j = 3
    i -= 1

print(list_tuples)

Output: [(3, 3), (3, 2), (3, 1), (2, 3), (2, 2), (2, 1), (1, 3), (1, 2), (1, 1)]


Conclusion

Python while loop is used to run a code block for specific number of times. We can use break and continue statements with while loop. The else block with while loop gets executed when the while loop terminates normally. The while loop is also useful in running a script indefinitely in the infinite loop.

Понравилась статья? Поделить с друзьями:
  • Python unindent does not match any outer indentation level ошибка
  • Python unicode error unicodeescape codec can t decode bytes in position
  • Python unicode error pandas
  • Python try except вывести текст ошибки
  • Python try except все ошибки