- Цикл while в Python
- Управление потоком инструкций: цикл While в Python
- Что такое цикл while в Python?
- Бесконечный цикл while в Python
- Else в цикле while
- Прерывания цикла while в Python
- Цикл while в Python и алгебра логики
- Алгебра логики
- Python While Loop with Multiple Conditions Using AND
- Python While Loop with Multiple Conditions Using OR
- Using a NOT Operator in a Python While Loop with Multiple Conditions
- How to Group Multiple Conditions in a Python While Loop
Цикл while в Python
Из этого материала вы узнаете, что такое циклы while, как они могут становиться бесконечными, как использовать инструкцию else в цикле while и как прерывать исполнение цикла.
Управление потоком инструкций: цикл While в Python
Как и другие языки программирования 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 есть два ключевых слова, с помощью которых можно преждевременно остановить итерацию цикла.
- Break — ключевое слово break прерывает цикл и передает управление в конец цикла
a = 1 while a 5: a += 1 if a == 3: break print(a) # 2
a = 1 while a 5: a += 1 if a == 3: continue print(a) # 2, 4, 5
Цикл while в Python и алгебра логики
В этом уроке познакомимся с алгеброй логики и циклом while в Python. Изучим подробнее на примере задания «Соответствие символов».
Алгебра логики
Мы уже рассматривали условия в Python для двух сравнений. Когда требуется больше сравнений, используется специальные операторы. Они объединяют два и более простых логических выражения. В таких случаях используются два логических оператора И (and) и ИЛИ (or).
Оператор and обозначается символов ∧, а операция называется конъюнкцией. Для получения истины результаты обоих простых выражений должны быть истинными. Если хотя бы в одном случае результатом будет ложным, то выражение будет ложным. Приведем таблицу истинности для логического оператора and.
Давайте рассмотрим работу подобного цикла на примере:
a = 10 i = 3 while a > i: print(i, "
Результат выполнения будет выглядеть так:
Часть кода выполняется столько раз, сколько условие было истинно. За счет увеличения i на каждом шаге удалось достигнуть такой величины, что условие цикла стало ложью.
Задание «Соответствие символов»
Необходимо написать программу, которая на вход получает строку и некий символ. Задача состоит в проверке наличия символа в приведенной строке.
S = input("введи строку: ") C = input("введи символ: ") size = len(S) # длина строки i = 0 while (S[i] != C) and (i < size-1): # выходим из цикла если нашли символ или если строка закончилась print(S[i],"
Проверим нашу программу. Для примера введем фразу «Hello world» и символ l, который включен в это выражение.
введи строку: Hello world введи символ: l H >>
Введем символ, который не включен в эту фразу:
введи строку: Hello world введи символ: z H
Курсы Робикс, в которых изучается этот материал.
Python While Loop with Multiple Conditions
In this tutorial, you’ll learn how to write a Python while loop with multiple conditions, including and and or conditions. You’ll also learn how to use the NOT operator as well as how to group multiple conditions.
The Quick Answer: Embed Conditions with AND or OR Operators in Your While Loop
What is a Python While Loop
A Python while loop is an example of iteration, meaning that some Python statement is executed a certain number of times or while a condition is true. A while loop is similar to a Python for loop, but it is executed different. A Python while loop is both an example of definite iteration, meaning that it iterates a definite number of times, and an example of indefinite iteration, meaning that it iterates an indefinite number of times.
Let’s take a quick look at how a while loop is written in Python:
while [condition]: [do something]
In the example above, the while loop will complete the step do something indefinitely, until the condition is no longer met.
while True: print('Welcome to datagy.io')
The program would run indefinitely, until the condition is not longer True. Because of this, we need to be careful about executing a while loop.
To see how we can stop a while loop in Python, let’s take a look at the example below:
In the sections below, you'll learn more about how the Python while loop can be implemented with multiple conditions. Let's get started!
Want to learn about Python for-loops? Check out my in-depth tutorial here, to learn all you need to know to get started!
Python While Loop with Multiple Conditions Using AND
Now that you've had a quick recap of how to write a Python while loop, let's take a look at how we can write a while loop with multiple conditions using the AND keyword.
In this case, we want all of the conditions to be true, whether or not there are two, three, or more conditions to be met.
To accomplish meeting two conditions, we simply place the and keyword between each of the conditions. Let's take a look at what this looks like:
a = 0 b = 10 while a < 4 and b >3: print(f'Hello! The value of a is and the value of b is .') a += 1 b -= 1 # Returns # Hello! The value of a is 0 and the value of b is 10. # Hello! The value of a is 1 and the value of b is 9. # Hello! The value of a is 2 and the value of b is 8. # Hello! The value of a is 3 and the value of b is 7.
We can see here that the code iterates only while both of the conditions are true. As soon as, in this case, a = 4 , the condition of a < 4 is no longer true and the code stops execution.
Now let's take a look at how we can implement an or condition in a Python while loop.
Python While Loop with Multiple Conditions Using OR
Similar to using the and keyword in a Python while loop, we can also check if any of the conditions are true. For this, we use the or keyword, which checks whether either of our conditions are true.
In order to implement this, we simply place the or keyword in between the two conditions. We can also use more than two conditions and this would work in the same way.
For easier learning, let's stick to two conditions:
a = 0 b = 10 while a < 4 or b >3: print(f'Hello! The value of a is and the value of b is .') a += 1 b -= 1 # Returns # Hello! The value of a is 0 and the value of b is 10. # Hello! The value of a is 1 and the value of b is 9. # Hello! The value of a is 2 and the value of b is 8. # Hello! The value of a is 3 and the value of b is 7. # Hello! The value of a is 4 and the value of b is 6. # Hello! The value of a is 5 and the value of b is 5. # Hello! The value of a is 6 and the value of b is 4.
We can see that by simply switching from and to or , that or code execute many more times. In fact, the code runs until neither condition is not longer true.
Using a NOT Operator in a Python While Loop with Multiple Conditions
Another important and helpful operator to apply in Python while loops is the not operator. What this operator does is simply reverse the truth of a statement. For example, if we wrote not True , then it would evaluate to False . This can be immensely helpful when trying to write your code in a more plan language style.
Let's see how we can apply this in one of our examples:
a = 0 b = 10 while a < 4 and not b < 3 : print(f'Hello! The value of a is and the value of b is .') a += 1 b -= 1 # Returns # Hello! The value of a is 0 and the value of b is 10. # Hello! The value of a is 1 and the value of b is 9. # Hello! The value of a is 2 and the value of b is 8. # Hello! The value of a is 3 and the value of b is 7.
Here our code checks that a is less than 4 and that b is not less than 3. Because of this, our code only executes here until a is equal to 4.
Next, let's take a look at how to group multiple conditions in a Python.
How to Group Multiple Conditions in a Python While Loop
There may be many times that you want to group multiple conditions, including mixing and and or statements. When you do this, it's important to understand the order in which these conditions execute. Anything placed in parentheses will evaluated against one another.
To better understand this, let's take a look at this example:
while (a or b) and c: print('Ok!')
In the code above, if either a or b evaluate to True and c is True then the code will run.
This is known as a Python truth table and it's an important concept to understand.
In essence, the parentheses reduce the expression to a single truth that is checked against, simplifying the truth statement significantly.
Now, let's take a look at a practical, hands-on example to better understand this:
a = 0 b = 10 c = 5 while (a < 4 or b >3) and c < 9: print(f'Hello! The value of a is , the value of b is , and the value of c is .') a += 3 b -= 3 c += 1 # Returns # Hello! The value of a is 0, the value of b is 10, and the value of c is 5. # Hello! The value of a is 3, the value of b is 7, and the value of c is 6. # Hello! The value of a is 6, the value of b is 4, and the value of c is 7.
We can see here that the code stops after the third iteration. The reason for this a is less than 4 and b is greater than 3 after the third iteration. Because neither of the conditions in the parentheses are met, the code stops executing.