Цикл while в Python
Цикл while («пока») позволяет выполнить одну и ту же последовательность действий, пока проверяемое условие истинно. Условие записывается после ключевого слова while и проверяется до выполнения тела цикла.
Цикл while используется, когда невозможно определить точное количество повторений цикла.
i = 0 # объявление переменной i для условия цикла
while i 5 : # ключевое слово ‘while’ и условие выполнение цикла
# тело цикла
print (i) # вывод значения переменной i
i += 1 # увеличение значения переменной i на единицу
Цикл while может быть бесконечным.
i = 0
while True : # условие всегда истинно
print (i)
i += 1
# Вывод:
>> 0
>> 1
>> 2
>> 3
>> 4
.
>> 999
.
# Это может продолжаться долго.
Выполнение цикла можно прерывать с помощью оператора break.
i = 0
while 1 : # условие всегда истинно
if i == 3 : # если i равно 3, то вызываем оператор break
break # оператор break прерывает выполнение цикла
print (i)
i += 1
Оператор continue начинает повторение цикла заново.
i = 0
while i 5 :
i += 1 #
if i % 2 == 1 : # если значение i нечетно, то вызываем оператор continue
continue # оператор continue начинает повторение цикла заново
# в случае вызова continue код ниже не выполнится
print (i)
Как и для цикла for, для цикла while мы можем записать конструкцию else.
x = 1
while x 5 :
print (x)
x += 1
else :
print ( ‘Цикл завершен’ )
Примеры
# Пользователь вводит числа A и B (A > B). Выведите все числа от A до B включительно.
A = int ( input ( ‘Введите число: ‘ ))
B = int ( input ( ‘Введите число: ‘ ))
# Пользователь вводит числа до тех пор, пока не введет 0.
# Выведите количество введенных чисел (0 считать не нужно).
n = int ( input ( ‘Введите число: ‘ ))
counter = 0 # счетчик введенных чисел
while n: # n неявно преобразуется в тип bool
# если n равно 0, то выполнение цикла прервется
n = int ( input ( ‘Введите число: ‘ )) # вводим очередное число
counter += 1 # увеличиваем счетчик
print ( f ‘Количество чисел ‘ )
# Ввод:
>> 1
>> 10
>> 100
>> 1000
>> 0
# Вывод:
>> Количество чисел 4
# Пользователь вводит число N (N > 1). Выведите его наименьший делитель.
N = int ( input ( ‘Введите число: ‘ ))
div = 2
while N % div != 0 :
div += 1
print ( f ‘Наименьший делитель равен ‘ )
# Ввод:
>> 10
# Вывод:
>> Наименьший делитель равен 2
# Ввод:
>> 15
# Вывод:
>> Наименьший делитель равен 3
# Ввод:
>> 17
# Вывод:
>> Наименьший делитель равен 17
Решение задач
Пользователь вводит числа A и B (A > B). Выведите четные числа от A до B включительно.
Пользователь вводит числа A и B (A # Ввод:
>> 1
>> 15
# Вывод:
>> 3
>> 6
>> 9
>> 12
>> 15
Пользователь вводит числа до тех пор, пока не введет 0. Выведите сумму введенных чисел (0 считать не нужно).
# Ввод:
>> 1
>> 15
>> 10
>> 11
>> 2
>> 0
# Вывод:
>> Сумма равна: 39
Пользователь вводит числа до тех пор, пока не введет 0. Выведите максимальное введенное число (0 считать не нужно).
# Ввод:
>> 1
>> 15
>> 10
>> 11
>> 2
>> 0
# Вывод:
>> Максимум равен: 15
Пользователь вводит числа до тех пор, пока не введет 0. Выведите минимальное введенное число (0 считать не нужно).
# Ввод:
>> 1
>> 15
>> 10
>> 11
>> 2
>> 0 # 0 не входит в последовательность
# Вывод:
>> Минимум равен: 1
Пользователь вводит число N. Выведите факториал число N. Факториал числа N — это произведение всех чисел от 1 до N включительно. Например, факториал числа 5 равен 120.
7. Фибоначчи (финальный босс)
Пользователь вводит число N. Выведите N-ное по счету число Фибоначчи. Последовательность чисел Фибоначчи рассчитывается по такой формуле: F(1) = 1, F(2) = 1, F(K) = F(K-2) + F(K-1). Идея такая: каждое следующее число равно сумму двух предыдущих.
Первые 10 чисел последовательности: 1 1 2 3 5 8 13 21 34 55 .
Python While Loops
With the while loop we can execute a set of statements as long as a condition is true.
Example
Print i as long as i is less than 6:
i = 1
while i while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i , which we set to 1.
The break Statement
With the break statement we can stop the loop even if the while condition is true:
Example
Exit the loop when i is 3:
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:
The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
Example
Print a message once the condition is false:
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
While loops
While loops, like the ForLoop, are used for repeating sections of code — but unlike a for loop, the while loop will not run n times, but until a defined condition is no longer met. If the condition is initially false, the loop body will not be executed at all.
As the for loop in Python is so powerful, while is rarely used, except in cases where a user’s input is required*, for example:
n = raw_input("Please enter 'hello':") while n.strip() != 'hello': n = raw_input("Please enter 'hello':")
However, the problem with the above code is that it’s wasteful. In fact, what you will see a lot of in Python is the following:
while True: n = raw_input("Please enter 'hello':") if n.strip() == 'hello': break
- Another version you may see of this type of loop uses while 1 instead of while True. In older Python versions True was not available, but nowadays is preferred for readability.
- Starting with Py2.3, the interpreter optimized while 1 to just a single jump. Using 1 was minutely faster, since True was not a keyword and might have been given a different value, which the interpreter had to look up, as opposed to loading a constant. As a programmer, it is up to you which style to use — but always remember that readability is important, and that while speed is also important, readability trumps it except in cases where timings are significantly different.
- Starting in Python 3, True, False, and None are keywords, so using while 1 no longer provides the tiny performance benefit used to justify it in earlier versions.
- See also: http://stackoverflow.com/questions/3815359/while-1-vs-for-whiletrue-why-is-there-a-difference
* If this were Wikipedia, the above statement would be followed by «citation needed.»
WhileLoop (last edited 2017-04-10 16:43:34 by SteveHolden )