Do while function in python

Python Do While – Loop Example

Dionysia Lemonaki

Dionysia Lemonaki

Python Do While – Loop Example

Loops are a useful and frequently used feature in all modern programming languages.

If you want to automate a specific repetitive task or prevent yourself from writing repetitive code in your programs, using a loop is the best option for that.

Loops are a set of instructions that run repeatedly until a condition is met. Let’s learn more about how loops work in Python.

Loops in Python

There are two types of loops built into Python:

Let’s focus on how you can create a while loop in Python and how it works.

What is a while loop in Python?

The general syntax of a while loop in Python looks like this:

while condition: execute this code in the loop's body 

A while loop will run a piece of code while a condition is True. It will keep executing the desired set of code statements until that condition is no longer True.

A while loop will always first check the condition before running.

If the condition evaluates to True then the loop will run the code within the loop’s body.

For example, this loop runs as long as number is less than 10 :

number = 0 while number < 10: print(f"Number is !") number = number + 1 
Number is 0! Number is 1! Number is 2! Number is 3! Number is 4! Number is 5! Number is 6! Number is 7! Number is 8! Number is 9! 

Here, the variable number is set to 0 initially.

number is then incremented by 1 . The condition is re-evaluated and it is again True, so the whole procedure repeats until number is equal to 9 .

This time Number is 9! is printed and number is incremented, but now number is equal to 10 so the condition is no longer met and therefore the loop is terminated.

It's possible that the while loop never runs if it doesn't meet the condition, like in this example:

Since the condition is always False, the instructions in the loop's body don't execute.

Don't create infinite loops

As you saw from the example above, while loops are typically accompanied by a variable whose value changes throughout the duration of the loop. And it ultimately determines when the loop will end.

If you do not add this line, you will create an infinite loop.

Читайте также:  Что такое питон разработчик

number will not be incremented and updated. It will always be set and remain at 0 and therefore the condition number < 10 will be True forever. This means that the loop will continue to loop forever.

 # don't run this number = 0 while number < 10: print(f"Number is !") 
Number is 0! Number is 0! Number is 0! Number is 0! Number is 0! Number is 0! Number is 0! . 

It is the same as doing this:

 #don't run this while True: print("I am always true") 

What if you find yourself in a situation like this?

Press Control C to escape and end the loop.

What is a do while loop?

The general syntax of a do while loop in other programming languages looks something like this:

For example, a do while loop in C looks like this:

#include int main(void) < int i = 10; do < printf("the value of i: %i\n", i); i++; >while( i

What is unique in do while loops is the fact that the code in the loop block will be executed at least one time.

The code in the statement runs one time and then the condition is checked only after the code is executed.

So the code runs once first and then the condition is checked.

If the condition checked evaluates to true, the loop continues.

There are cases where you would want your code to run at least one time, and that is where do while loops come in handy.

For example, when you're writing a program that takes in input from users you may ask for only a positive number. The code will run at least once. If the number the user submits is negative, the loop will keep on running. If it is positive, it will stop.

Python does not have built-in functionality to explicitly create a do while loop like other languages. But it is possible to emulate a do while loop in Python.

How to emulate a do while loop in Python

To create a do while loop in Python, you need to modify the while loop a bit in order to get similar behavior to a do while loop in other languages.

As a refresher so far, a do while loop will run at least once. If the condition is met, then it will run again.

The while loop, on the other hand, doesn't run at least once and may in fact never run. It runs when and only when the condition is met.

So, let's say we have an example where we want a line of code to run at least once.

secret_word = "python" counter = 0 while True: word = input("Enter the secret word: ").lower() counter = counter + 1 if word == secret_word: break if word != secret_word and counter > 7: break 

The code will run at least one time, asking for user input.

Читайте также:  Python get code path

It is always guaranteed to run at least once, with True , which otherwise creates an infinite loop.

If the user inputs the correct secret word, the loop is terminated.

If the user enters the wrong secret word more than 7 times, then the loop will be completely exited.

The break statement allows you to control the flow of a while loop and not end up with an infinite loop.

break will immediately terminate the current loop all together and break out of it.

So this is how you create the a similar effect to a do while loop in Python.

The loop always executes at least once. It will continue to loop if a condition is not met and then terminate when a condition is met.

Conclusion

You now know how to create a do while loop in Python.

If you're interested in learning more about Python, you can watch the 12 Python Projects video on freeCodeCamp's YouTube channel. You'll get to build 12 projects and it's geared towards beginners.

freeCodeCamp also has a free Python Certification to help you gain a good understanding and a well rounded overview of the important fundamentals of the language.

You'll also get to build five projects at the end of the course to practice what you've learned.

Thanks for reading and happy learning!

Источник

Подробный разбор цикла while в Python

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

Что такое цикл?

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

В Python есть два основных вида циклов:

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

Цикл while

Суть работы цикла while очень проста. Работает он так: ваши инструкции выполняются, пока условие истинно.

Цикл while проверяет условие перед каждой итерацией цикла. Если возвращается True , то выполняется блок кода внутри цикла.

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

while 1

А теперь напишем небольшую программу. Это простой цикл, выводящий в консоль числа от 1 до 10.

Как вы можете заметить, тело цикла выполняется, пока x меньше или равно 10. Если вы присвоите x значение 20, то цикл не запустится вообще.

Читайте также:  Метод зейделя питон код

Цикл do-while

Есть две вариации цикла while . Первая — непосредственно сам while , вторая — do-while . Разница заключается в том, что do-while запустится хотя бы один раз.

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

Цикл while

Цикл do-while реализован в большинстве языков программирования, но в Python такого оператора нет. Тем не менее, его можно с легкостью имитировать — например, с помощью функций.

Давайте напишем код, имитирующий цикл do-while . Все нужные инструкции мы поместим внутри функции.

x = 20 def run_commands(x): print(x) run_commands(x) x += 1 while x 

Эта программа запускает run_commands() еще до цикла while . Но сам цикл while не запустится: x равен 20.

Оператор else

Если вы хотите выполнить блок кода, когда проверка условия возвращает False , — добавьте оператор else .

Добавим в наш код else . Внутри этого блока напишем код, который будет выводить в консоль Готово . Выполнится этот блок только после того, как в консоль выведутся числа от 1 до 10.

Эта программа выведет в консоль числа от 1 до 10. Как только x станет равно 11, результатом проверки условия будет False . После этого выполнится блок кода else .

Однострочное объявление while

Если внутри цикла while у вас только одна строка — можно воспользоваться однострочным вариантом. Делается это так:

Будьте осторожны — этот цикл бесконечный.

Бесконечные циклы

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

Этот цикл — бесконечный. Внутри цикла нет команды, которая изменяет значение x . Поэтому условие x >= 1 всегда истинно. Именно из-за этого цикл будет запускаться бесконечное количество раз.

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

Управление циклом

С циклом разобрались. Наконец мы можем перейти к операторам его управления.

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

Break

Этот оператор позволяет завершить цикл, если проверка условия возвращает True .

Выполнение цикла прекращается, когда x становится равно 5 — даже если x больше или равно 1.

Continue

Допустим, вам нужно пропустить итерацию цикла, если выполняется какое-то условие. Но цикл вы не хотите завершать до тех пор, пока проверка его условия не вернет False .

В этом случае вам нужно использовать ключевое слово continue :

Как видите, цикл выводит в консоль все числа от 1 до 10 кроме 5. Когда x становится равен 5, оставшаяся часть команд не выполняется, а начинается следующая итерация цикла.

Источник

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