Как пишется цикл while python

Из этого материала вы узнаете, что такое циклы while, как они могут становиться бесконечными, как использовать инструкцию else в цикле while и как прерывать исполнение цикла.

Как и другие языки программирования Python включает несколько инструкций для управления потоком. Одна из таких — if else. Еще одна — циклы. Циклы используются в тех случаях, когда нужно повторить блок кода определенное количество раз.

Что такое цикл while в Python?

Цикл while используется в Python для неоднократного исполнения определенной инструкции до тех пор, пока заданное условие остается истинным. Этот цикл позволяет программе перебирать блок кода.

while test_expression:
    body of while

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

Рассмотрим пример, чтобы лучше понять.

a = 1

while a < 10:
    print('Цикл выполнился', a, 'раз(а)')
    a = a+1
print('Цикл окончен')

Вывод:

Цикл выполнился 1 раз
Цикл выполнился 2 раз
Цикл выполнился 3 раз
Цикл выполнился 4 раз
Цикл выполнился 5 раз
Цикл выполнился 6 раз
Цикл выполнился 7 раз
Цикл выполнился 8 раз
Цикл выполнился 9 раз
Цикл окончен

Бесконечный цикл while в Python

Бесконечный цикл while — это цикл, в котором условие никогда не становится ложным. Это значит, что тело исполняется снова и снова, а цикл никогда не заканчивается.

Следующий пример — бесконечный цикл:

a = 1

while a==1:
    b = input('Как тебя зовут?')
    print('Привет', b, ', Добро пожаловать')

Если запустить этот код, то программа войдет в бесконечный цикл и будет снова и снова спрашивать имена. Цикл не остановится до тех пор, пока не нажать Ctrl + C.

Else в цикле while

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

a = 1

while a < 5:
   print('условие верно')
   a = a + 1
else:
   print('условие неверно')

Этот пример демонстрирует принцип работы else в цикле while.

Вывод:

условие верно
условие верно
условие верно
условие верно
условие неверно

Программа исполняет код цикла while до тех, пока условие истинно, то есть пока значение a меньше 5. Поскольку начальное значение a равно 1, а с каждым циклом оно увеличивается на 1, условие станет ложным, когда программа доберется до четвертой итерации — в этот момент значение a изменится с 4 до 5. Программа проверит условие еще раз, убедится, что оно ложно и исполнит блок else, отобразив «условие неверно».

Прерывания цикла while в Python

В Python есть два ключевых слова, с помощью которых можно преждевременно остановить итерацию цикла.

  1. Break — ключевое слово break прерывает цикл и передает управление в конец цикла
    a = 1
    while a < 5:
        a += 1
        if a == 3:
    	break
        print(a) # 2
    
  2. Continue — ключевое слово continue прерывает текущую итерацию и передает управление в начало цикла, после чего условие снова проверяется. Если оно истинно, исполняется следующая итерация.
a = 1

while a < 5:
    a += 1
    if a == 3:
	continue
    print(a)  # 2, 4, 5

Обучение с трудоустройством

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 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

В прошлой статье мы изучали цикл 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. Методы работы с файлами и файловой системой
  16. Регулярные выражения

Назад в начало

Цикл while («пока») позволяет выполнить одну и ту же последовательность действий, пока проверяемое условие истинно. Условие записывается после ключевого слова while и проверяется до выполнения тела цикла.

Цикл while используется, когда невозможно определить точное количество повторений цикла.

i = 0 # объявление переменной i для условия цикла

while i < 5: # ключевое слово ‘while’ и условие выполнение цикла

    # тело цикла

    print(i) # вывод значения переменной i

    i += 1 # увеличение значения переменной i на единицу

# Вывод:

>> 0

>> 1

>> 2

>> 3

>> 4

Цикл 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

# Вывод:

>> 0

>> 1

>> 2

Оператор continue начинает повторение цикла заново.

i = 0

while i < 5:

    i += 1 #

    if i % 2 == 1: # если значение i нечетно, то вызываем оператор continue

        continue # оператор continue начинает повторение цикла заново

    # в случае вызова continue код ниже не выполнится

    print(i)

# Вывод:

>> 0

>> 2

>> 4

Как и для цикла for, для цикла while мы можем записать конструкцию else.

x = 1

while x < 5:

    print(x)

    x += 1

else:

    print(‘Цикл завершен’)

# Вывод:

>> 1

>> 2

>> 3

>> 4

>> Цикл завершен

Примеры

1. Числа от A до B

# Пользователь вводит числа A и B (A > B). Выведите все числа от A до B включительно.


A = int(input(‘Введите число: ‘))

B = int(input(‘Введите число: ‘))

while A >= B:

    print(A)

    A -= 1

# Ввод:

>> 12

>> 7

# Вывод:

>> 12

>> 11

>> 10

>> 9

>> 8

>> 7

# Ввод:

>> 5

>> 2

# Вывод:

>> 5

>> 4

>> 3

>> 2

2. Много чисел

# Пользователь вводит числа до тех пор, пока не введет 0.

# Выведите количество введенных чисел (0 считать не нужно).


n = int(input(‘Введите число: ‘))

counter = 0 # счетчик введенных чисел

while n: # n неявно преобразуется в тип bool

    # если n равно 0, то выполнение цикла прервется

    n = int(input(‘Введите число: ‘)) # вводим очередное число

    counter += 1 # увеличиваем счетчик


print(f‘Количество чисел {counter})

# Ввод:

>> 1

>> 10

>> 100

>> 1000

>> 0

# Вывод:

>> Количество чисел 4

3. Наименьший делитель

# Пользователь вводит число N (N > 1). Выведите его наименьший делитель.

N = int(input(‘Введите число: ‘))

div = 2

while N % div != 0:

    div += 1

print(f‘Наименьший делитель равен {div})

# Ввод:

>> 10

# Вывод:

>> Наименьший делитель равен 2

# Ввод:

>> 15

# Вывод:

>> Наименьший делитель равен 3

# Ввод:

>> 17

# Вывод:

>> Наименьший делитель равен 17

Решение задач

1. Четные от A до B

Пользователь вводит числа A и B (A > B). Выведите четные числа от A до B включительно.

# Ввод:

>> 10

>> 1

# Вывод:

>> 10

>> 8

>> 6

>> 4

>> 2

2. От A до B на три

Пользователь вводит числа A и B (A < B, A меньше B). Выведите числа от A до B включительно, которые делятся на три.

# Ввод:

>> 1

>> 15

# Вывод:

>> 3

>> 6

>> 9

>> 12

>> 15

3. Сумма чисел

Пользователь вводит числа до тех пор, пока не введет 0. Выведите сумму введенных чисел (0 считать не нужно).

# Ввод:

>> 1

>> 15

>> 10

>> 11

>> 2

>> 0

# Вывод:

>> Сумма равна: 39

4. Максимум

Пользователь вводит числа до тех пор, пока не введет 0. Выведите максимальное введенное число (0 считать не нужно).

# Ввод:


>> 1

>> 15

>> 10

>> 11

>> 2

>> 0

# Вывод:

>> Максимум равен: 15

5. Минимум

Пользователь вводит числа до тех пор, пока не введет 0. Выведите минимальное введенное число (0 считать не нужно).

# Ввод:

>> 1

>> 15

>> 10

>> 11

>> 2

>> 0 # 0 не входит в последовательность

# Вывод:

>> Минимум равен: 1

6. Факториал

Пользователь вводит число N. Выведите факториал число N. Факториал числа N — это произведение всех чисел от 1 до N включительно. Например, факториал числа 5 равен 120.

# Ввод:

>> 5

# Вывод:

>> 120

# Ввод:

>> 3

# Вывод:

>> 6

# Ввод:

>> 4

# Вывод:

>> 24

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 …

# Ввод:

>> 5

# Вывод:

>> 5

# Ввод:

>> 10

# Вывод:

>> 55

# Ввод:

>> 8

# Вывод:

>> 21

1. Цикл while

Цикл while (“пока”) позволяет выполнить
одну и ту же последовательность действий, пока проверяемое условие истинно.
Условие записывается до тела цикла и проверяется до выполнения тела цикла.
Как правило, цикл while используется, когда невозможно
определить точное значение количества проходов исполнения цикла.

Синтаксис цикла while в простейшем случае выглядит так:

while условие:
    блок инструкций

При выполнении цикла while сначала проверяется условие.
Если оно ложно, то выполнение цикла прекращается и управление
передается на следующую инструкцию после тела цикла while.
Если условие истинно, то выполняется инструкция, после чего условие
проверяется снова и снова выполняется инструкция.
Так продолжается до тех пор, пока условие будет истинно.
Как только условие станет ложно, работа цикла завершится и
управление передастся следующей инструкции после цикла.

Например, следующий фрагмент программы напечатает на экран
квадраты всех целых чисел от 1 до 10. Видно, что цикл
while может заменять цикл for ... in range(...):

i = 1
while i <= 10:
    print(i ** 2)
    i += 1

В этом примере переменная i внутри цикла изменяется от 1 до 10.
Такая переменная, значение которой меняется с каждым новым проходом цикла,
называется счетчиком. Заметим, что после выполнения этого фрагмента
значение переменной i будет равно 11,
поскольку именно при i == 11 условие i <= 10 впервые
перестанет выполняться.

Вот еще один пример использования цикла while
для определения количества цифр натурального числа n:

n = int(input())
length = 0
while n > 0:
    n //= 10  # это эквивалентно n = n // 10
    length += 1
print(length)

В этом цикле мы отбрасываем по одной цифре числа, начиная с конца,
что эквивалентно целочисленному делению на 10 (n //= 10),
при этом считаем в переменной length, сколько раз это было сделано.

В языке Питон есть и другой способ решения этой задачи:
length = len(str(i)).

2. Инструкции управления циклом

После тела цикла можно написать слово else:
и после него блок операций, который будет
выполнен один раз после окончания цикла, когда проверяемое
условие станет неверно:

i = 1
while i <= 10:
    print(i)
    i += 1
else:
    print('Цикл окончен, i =', i)

Казалось бы, никакого смысла в этом нет, ведь эту же инструкцию можно
просто написать после окончания цикла. Смысл появляется только
вместе с инструкцией break. Если во время выполнения Питон встречает
инструкцию break внутри цикла, то он сразу же прекращает выполнение этого цикла и выходит из него.
При этом ветка else исполняться не будет. Разумеется, инструкцию break осмыленно
вызывать только внутри инструкции if, то есть она должна выполняться
только при выполнении какого-то особенного условия.

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

a = int(input())
while a != 0:
    if a < 0:
        print('Встретилось отрицательное число', a)
        break
    a = int(input())
else:
    print('Ни одного отрицательного числа не встретилось')

Во втором варианте программы сначала на вход подается количество элементов последовательности, а затем
и сами элементы. В таком случае удобно воспользоваться циклом for. Цикл for
также может иметь ветку else и содержать инструкции break внутри себя.

n = int(input())
for i in range(n):
    a = int(input())
    if a < 0:
        print('Встретилось отрицательное число', a)
        break    
else:
    print('Ни одного отрицательного числа не встретилось')

Другая инструкция управления циклом —
continue (продолжение цикла). Если эта инструкция
встречается где-то посередине цикла, то пропускаются все оставшиеся
инструкции до конца цикла, и исполнение цикла продолжается
со следующей итерации.

Если инструкции break и continue содержатся внутри нескольких вложенных
циклов, то они влияют лишь на исполнение самого внутреннего цикла. Вот не самый интеллектуальный пример,
который это демонстрирует:

for i in range(3):
    for j in range(5):
        if j > i:
            break
        print(i, j)

Увлечение инструкциями break и continue
не поощряется, если можно обойтись без их использования. Вот типичный пример плохого использования инструкции break
(данный код считает количество знаков в числе).

n = int(input())
length = 0
while True:
    length += 1
    n //= 10
    if n == 0:
        break
print('Длина числа равна', length)

Гораздо лучше переписать этот цикл так:

n = int(input())
length = 0
while n != 0:
    length += 1
    n //= 10
print('Длина числа равна', length)

Впрочем, на Питоне можно предложить и более изящное решение:

n = int(input())
print('Длина числа равна', len(str(n)))

3. Множественное присваивание

В Питоне можно за одну инструкцию присваивания изменять значение сразу нескольких переменных. Делается это так:

Этот код можно записать и так:

Отличие двух способов состоит в том, что множественное присваивание в первом способе меняет значение двух переменных одновременно.

Если слева от знака «=» в множественном присваивании должны стоять через запятую имена переменных, то справа могут стоять произвольные выражения,
разделённые запятыми. Главное, чтобы слева и справа от знака присваивания было одинаковое число элементов.

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

a = 1
b = 2
tmp = a
a = b
b = tmp
print(a, b)  
# 2 1

В Питоне то же действие записывается в одну строчку:

a = 1
b = 2
a, b = b, a
print(a, b)  
# 2 1


Ссылки на задачи доступны в меню слева. Эталонные решения теперь доступны на странице самой задачи.

В статье расскажем об особенностях работы циклов while в Python и разберем проблемы, которые возникают у начинающих «питонистов».

Циклические конструкции в языках программирования используются для повторения отдельных блоков кода до тех пор, пока не будет выполнено определенное условие. Одним из таких инструментов в Питоне является конструкция while. Понять работу цикла while в Python 3 нетрудно: просто переведите это слово с английского, как «до тех пор, пока». Пример кода:

number = 0
while number < 3:
    print('Условие истинно, переменная number меньше трех и сейчас равна', number, ', поэтому цикл продолжает выполняться.')
    number += 1
print('Мы вышли из цикла, так как значение переменной number стало равным', number, ', а условие перестало быть истинным.')
input('Нажмите Enter для выхода')

Запустив эту программу, получим вполне наглядный вывод:

Условие истинно, переменная number меньше трех и сейчас равна 0 , поэтому цикл продолжает выполняться.

Мы вышли из цикла, так как значение переменной number стало равным 3 , а условие перестало быть истинным.

А вот пример части вполне реальной программы:

while score1 < 5 and score2 < 5:
    print('Игра продолжается, так как никто не набрал 5 очков.')

Если буквально переводить с Python на русский (а начинающим так делать полезно), то инструкция программы такая: до тех пор, пока количество очков первого игрока (score1) или количество очков второго игрока (score2) меньше 5, выводить на экран сообщение «Игра продолжается, так как никто не набрал 5 очков».

Интерпретатор рассматривает условие while (в данном случае: score1 < 5 and score2 < 5) как истинное, True, и перейдет к следующему блоку кода только тогда, когда оно станет ложным, False (то есть один из игроков наберет 5 очков, и игра закончится). Чтобы было понятнее, давайте взглянем на эту простую программу для игры в кости и рассмотрим, как она работает:

import random

score1 = 0
score2 = 0
die1 = 0
die2 = 0

input('Первый игрок бросает кубик, нажмите Enter!n')

while score1 < 5 and score2 < 5:

    die1 = random.randint(1, 6)
    print(die1,'n')
    input('Теперь бросает кубик второй игрок, нажмите Enter!n')

    die2 = random.randint(1, 6)
    print(die2,'n')

    if die1 > die2:
        score1 += 1
    elif die1 < die2:
        score2 += 1
    else:
        print('Ничьяn')
    print('Счёт', score1, ':', score2,'n')
    input('Нажмите Enter!n')

if score1 > score2:
    input('Победил первый игрок! Нажмите Enter для выхода')
else:
    input('Победил второй игрок! Нажмите Enter для выхода')

Для получения случайных значений при броске кубиков нам понадобится функция random, поэтому сначала вызываем ее, а затем создаем переменные для подсчета выигранных каждым игроком партий и для результатов бросков кубика. А все броски будут выполняться внутри блока с таким условием:

while score1 < 5 and score2 < 5:

Это означает: до тех пор, пока количество выигранных партий первым и вторым игроком не достигнет пяти, игра не прекратится. Обратите внимание, что для создания условия мы использовали логический оператор and: это обеспечит выход из игры, как только значение одной из переменных (score1 или score2) достигнет пяти (в случае с or выход произошел бы только при выполнении обоих условий).

Дальше выполняются броски: они имитируются нажатием на Enter и присвоением случайных значений переменным die1 и die2. Затем эти переменные сравниваются, и в результате сравнения очко присуждается первому или второму игроку, а в случае ничьей партия переигрывается.

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

Бесконечные циклы и борьба с ними

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

number = 1
while number > 0:
    print(number)
    number += 1

Запустите ее в интерпретаторе Python и посмотрите на результат. Числа будут выводиться бесконечно (на практике — до того момента, пока у компьютера не закончится свободная память). Теперь убьем программу, закрыв IDE, и разберем, что же здесь случилось:

number = 1

Вводим переменную number и задаем ей значение.

while number > 0:
    print(number)
    number += 1

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

number = 1
while number == 1:
    print(number)

Но одно дело создать такую ситуацию искусственно, однако чаще всего бесконечные циклы создаются случайно, потому что программисты их не предусмотрели:

import random
fuel = 30
cities = 0
consumption = random.randint(1, 10)
while fuel != 0:
    cities += 1
    fuel -= consumption
    consumption = random.randint(1, 10)
    print('Вы проехали',cities,'городов')
input('Топливо закончилось, нажмите Enter для выхода из машины')

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


Вы проехали 298 городов
Вы проехали 299 городов
Вы проехали 300 городов
...

Разбираемся, что здесь не так. Для этого слегка перепишем предпоследнюю строчку:

print('Вы проехали',cities,'городов, и у вас осталось в баке',fuel,'литров')

Вы проехали 6 городов, и у вас осталось в баке 5 литров
Вы проехали 7 городов, и у вас осталось в баке -4 литров
Вы проехали 8 городов, и у вас осталось в баке -8 литров

Проблема найдена: в условиях у нас было выставлено while fuel != 0, однако переменная fuel так и не приняла значения 0 (если бы это случилось волею рандома, программа бы завершилась), а ее значение сразу стало отрицательным. Так как количество топлива в баке не было равным нулю, условие осталось истинным, и программа продолжила выполнение дальше. Осталось изменить всего лишь один знак в строке условия, и всё заработает как надо:

import random
fuel = 30
cities = 0
consumption = random.randint(1, 10)
while fuel > 0:
    cities += 1
    fuel -= consumption
    consumption = random.randint(1, 10)
    print('Вы проехали',cities,'городов')
input('Топливо закончилось, нажмите Enter для выхода из машины')

Теперь условие будет истинно только до того момента, пока fuel будет больше нуля. Вот что у нас получилось в итоге:

Вы проехали 5 городов
Топливо закончилось, нажмите Enter для выхода из машины

Условие цикла while оказалось выполненным, и программа перешла к следующему блоку.

Пишем программу с while и ветвлениями

Ветвления реализуются с помощью условных операторов if-elif-else, а в сочетании с циклами делают программы очень разнообразными. Давайте напишем несложный спортивный симулятор. Представим, что в очередном финале хоккейного Кубка Гагарина встретились СКА и ЦСКА. Основное время не выявило победителя, поэтому игра продолжилась до первой заброшенной шайбы:

import random

goal1 = 0
goal2 = 0
time = 1

while goal1 == 0 and goal2 == 0:    
    attack = random.randint(1, 2)
    if attack == 1:
        shoot = random.randint(1, 2)
        if shoot == 1:
            keeper = random.randint(1, 2)
            if keeper == 1:
                print('Шайба отбита вратарём ЦСКА, матч продолжается')
                time += 1
                attack = random.randint(1, 2)
            else:
                print('Гооол! СКА побеждает 1:0!')
                goal1 += 1
        else:
            print('Нападающий СКА пробил мимо ворот')
            time += 1
            attack = random.randint(1, 2)
    else:
        shoot = random.randint(1, 2)
        if shoot == 1:
            keeper = random.randint(1, 2)
            if keeper == 1:
                print('Шайба отбита вратарём СКА, матч продолжается')
                time += 1
                attack = random.randint(1, 2)
            else:
                print('Гооол! ЦСКА побеждает 0:1!')
                goal2 += 1
        else:
            print('Нападающий ЦСКА пробил мимо ворот')
            time += 1
            attack = random.randint(1, 2)

print('Матч окончен на', time, 'минуте дополнительного времени.')
input()

Как видите, while здесь выполняет ключевую функцию, обеспечивая выход при выполнении главного условия. Кстати, цикл этот теоретически бесконечный, хотя представить, что генератор случайных чисел всё время будет выбирать «неголевые» числа, сложно. Тем не менее полезно ограничить матч. Подумайте, как это можно сделать (подсказка: добавить условие для переменной time, установив максимальное количество минут).

А у нас первый овертайм получился напряженным, соперники по четыре раза пытались поразить ворота друг друга, и в итоге это удалось москвичам:

Нападающий СКА пробил мимо ворот
Шайба отбита вратарём СКА, матч продолжается
Шайба отбита вратарём ЦСКА, матч продолжается
Нападающий СКА пробил мимо ворот
Нападающий ЦСКА пробил мимо ворот
Шайба отбита вратарём ЦСКА, матч продолжается
Шайба отбита вратарём СКА, матч продолжается
Шайба отбита вратарём СКА, матч продолжается
Гооол! ЦСКА побеждает 0:1!
Матч окончен на 9 минуте дополнительного времени.

Примерно так устроены все спортивные менеджеры и симуляторы — с той разницей, конечно, что на результат там влияет множество факторов. А принцип работы любых сложных программ одинаков: всё организуется при помощи циклов, условий и интерактивных элементов, один из которых — функция input().

Операторы прерывания цикла

«Верными помощниками» while являются операторы break и continue, без которых код многих программ был бы не таким удобным. break завершает цикл досрочно при выполнении некоторого условия, а continue игнорирует определенные итерации. Эти операторы позволяют значительно улучшить программу, при этом их синтаксис прост. Вот пример изящного решения с break и continue для обработки ошибок без вылета приложения на рабочий стол:

while True:
    try:
        number = int(input('Введите число: '))
        break
    except ValueError:
        print('Вы напечатали что-то другое')
        continue
print('Спасибо!')

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

Понравилась статья? Поделить с друзьями:
  • Как пишется цигель
  • Как пишется цигейковая шуба
  • Как пишется цивилизация на английском
  • Как пишется цианистый калий правильно
  • Как пишется цианид калия