While два условия python

Цикл while c двумя условиями

Всем доброго времени суток!
Проблема в следующем: не могу понять как создать цикл while с двумя условиями.
В инете инфы не нашел.
У самого получается или невыполнение условия или ошибка.

Задача: две переменные сравниваются со строкой

Мои не рабочие учебные варианты:

a= input("Введите a:\n") b= input("Введите b:\n") while (a and b) != ("стоп" or "Стоп" or "СТОП"): print("Хорошо") else: print ("всему конец")
a= input("Введите a:\n") b= input("Введите b:\n") while (a or b) != ("стоп" or "Стоп" or "СТОП"): print("Хорошо") else: print ("всему конец")

Цикл while c 2 условиями
Добрый день все. пытаюсь решить задачу при которой необходима работа цикли while с 2 условиями: .

Почему в операторе if с двумя условиями одно условие игнорируется
Есть список: a = Задача: удалить все строки, содержащие литеру «а». for i, j in enumerate(a).

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

Цикл с несколькими условиями
Привет, вот мои наброски (я учусь Питону несколько дней, не обессудьте). Моя проблема заключается в.

Эксперт Python

a= input("Введите a:\n") b= input("Введите b:\n") while a.lower() != "стоп" and b.lower() != "стоп": print("Хорошо") . # Ваш код a= input("Введите a:\n") b= input("Введите b:\n") else: print ("всему конец")
(a != "стоп" and a != "Стоп" and a != "СТОП") and (b != "стоп" and b != "Стоп" and b != "СТОП")

ЦитатаСообщение от Gdez Посмотреть сообщение

Вариант хорош, если в принципе не важно как «стоп» будет введен, если есть ограничения либо все в одном регистре, либо заглавная буква в верхнем такой вариант не прокатит.

Эксперт Python

ЦитатаСообщение от blackgeneral Посмотреть сообщение

ЦитатаСообщение от blackgeneral Посмотреть сообщение

while 'стоп' not in (a.lower(), b.lower())

Gdez, kazak, Спасибо, работает, но не понятно: по логике вещей вы используете «И», а по таблице истинности это значит (И «a» » И «b», т.е. вместе),но код работает и в случае «И» и в случае «ИЛИ». Почему?

Добавлено через 3 минуты
Welemir1, а Вы введите в поиск «цикл while с двумя условиями + python» или «цикл while с несколькими условиями + python» и посмотрите много ли Вам вывалится вариантов.
Ржать над другими легче всего.

Эксперт Python

blackgeneral, аз ю виш!
вот написал

первая же ссылка не считая рекламы
(вставить сюда не могу, форум запрещает ссылки на ру_стак_оверфлоу)

Эксперт PythonЭксперт Java

ЦитатаСообщение от Welemir1 Посмотреть сообщение

Эксперт PythonЭксперт Java

ЦитатаСообщение от blackgeneral Посмотреть сообщение

ЦитатаСообщение от iSmokeJC Посмотреть сообщение

Возможно Вы правы. Я ее открывал, но не понял их примера. Примеры, которые написали на форуме более понятны ))

ЦитатаСообщение от iSmokeJC Посмотреть сообщение

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

ЦитатаСообщение от kazak Посмотреть сообщение

эм. вы о чем? а если еще 100500 вариантов будет. допустим пару в верхнем регистре остальные в нижнем а вот какие неизвестно. так и будете писать все возможные варианты?
a != «стоп» and a != «Стоп» and a != «СТОП» and a != «СтоП» and a != «СТоп» and a != «СтОп» and a != «стОП» and a != «сТоП».

Читайте также:  Putting background image in html

Эксперт функциональных языков программированияЭксперт Python

ЦитатаСообщение от blackgeneral Посмотреть сообщение

ЦитатаСообщение от kazak Посмотреть сообщение

a.lower() != «стоп»
Вариант хорош, если в принципе не важно как «стоп» будет введен, если есть ограничения либо все в одном регистре, либо заглавная буква в верхнем такой вариант не прокатит.

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

Добавлено через 1 минуту

ЦитатаСообщение от Semen-Semenich Посмотреть сообщение

эм. вы о чем? а если еще 100500 вариантов будет. допустим пару в верхнем регистре остальные в нижнем а вот какие неизвестно. так и будете писать все возможные варианты?
a != «стоп» and a != «Стоп» and a != «СТОП» and a != «СтоП» and a != «СТоп» and a != «СтОп» and a != «стОП» and a != «сТоП».

from time import sleep x,n=True,'' while x and (n := input("Введите что-нибудь, кроме 'стопэ' или 'выход': "))!='стопэ': if n=='выход': x=False else: print('продолжаем разговор') sleep(2) print("End")

ЦитатаСообщение от Catstail Посмотреть сообщение

Допустим.
Но по сути вопроса Вы же поняли как это называется?
Сказать правильную формулировку нельзя? Или нужно обязательно «тыкнуть»?

ЦитатаСообщение от Ципихович Эндрю Посмотреть сообщение

ЦитатаСообщение от blackgeneral Посмотреть сообщение

ЦитатаСообщение от blackgeneral Посмотреть сообщение

это ж клад, чтобы Не зайти в ветку
Не равно х или хх или ххх
понимаете?
тем более, что слева от НЕ равно тоже засада (a and b)

Эксперт функциональных языков программированияЭксперт Python

ЦитатаСообщение от blackgeneral Посмотреть сообщение

— не вполне. Имелось в виду это:

a= input("Введите a: ") b= input("Введите b: ") while (a.upper() != "СТОП") and (b.upper() != "СТОП"): print("Хорошо") else: print ("всему конец")

Цикл с двумя условиями
Подскажите, как написать, цикл который бы останавливался при значении переменной choice равной 1.

Цикл с двумя разными условиями
Вот таблица, с заполненными и пустыми значениями. Сейчас он проверяет поле upak и выводит.

Макрос Цикл с двумя условиями и несколькими переменными
Нужна помощь. Требуется макрос. Лист 1: имеются столбцы 1,2,3.В первом столбце даты, во втором.

Не могу ни как реализовать mysql запрос с двумя условиями и с двумя JOIN
Здравствуйте! Задавал подобный вопрос на другом форуме, пока что за неделю ни кто не помог.

С двумя условиями.
Задан целочисленный одномерный массив A из N элементов. Найти номер последнего минимального.

СчётЕсли() с двумя условиями
Как подсчитать количество всех элементов столбца "Bbb" которые меньше "1", но только если рядом в.

Тригер с двумя условиями
Помогите поправить условие в триггере пробовал разные вариации не получается сделать 2 шаг.. .

Источник

Python While Loop with Multiple Conditions

Python While Loop Multiple Conditions Cover Image

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

Quick Answer - Python While Loop Multiple Conditions

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.

Читайте также:  Фон для TR

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.

Читайте также:  Url запрос на java

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.

Источник

Оцените статью