Что такое while true на python
Перейти к содержимому

Что такое while true на python

  • автор:

What Does while true do in Python?

Popular loop structures like «While true» may be found in various computer languages, including Python 3.11.1. This kind of loop continues indefinitely until a specific condition is satisfied, at which point it ends. This loop is very helpful when you need to carry out the same operation repeatedly until a particular event occurs.

The following Python code demonstrates the syntax for the while true loop.

Syntax

while True: # Code block to be executed repeatedly

The keyword “while” precedes the condition «True» in the loop’s first declaration. This boolean value evaluates to True every time, so it indicates that the loop will continue until something else breaks it. Any repeatable code can be placed inside the loop.

Example

So here are a few basic examples of how a “while True” statement can be used in Python −

while True: print("Hello, world!")

Output

Hello, World!

From the above code snippet,

  • As the condition True is always true, the while True statement generates a loop that will keep repeating forever.
  • «Hello, world!» is the argument given to the print() method inside the loop. The phrase «Hello, world!» will be printed to the console.

Example

Now let’s understand the next example with a counter.

count = 0 while True: count += 1 if count > 15: break print(count)

Output

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

This is because the loop starts with the variable count equal to 0, and then increments it by 1 on each iteration until it reaches 15.

  • The while True statement in the loop establishes an infinite loop that runs continuously until the break statement is used to end it.
  • The += operator is used in the loop to add 1 to a counter variable’s count throughout each iteration.
  • The loop is ended using the break statement if the count value is larger than 15.
  • To output the value of the count to the console for each iteration of the loop, the print() function is used.

When you need to repeat an action until a specific event occurs, the «while true» loop is a practical choice. For instance, you may use the «while true» loop to keep questioning the user for input until they provide the proper response and an «if» statement inside the loop to check the accuracy of their response. The loop will continue to run and the user will be prompted once more if the response is inaccurate. If the response is accurate, on the other hand, the loop will end and the program will go to the next line of code.

Here is an example of how you could use the «while true» loop to accomplish this task in Python −

Example

while True: user_input = input("Please enter a valid response: ") if user_input == "yes": print("Thank you for your response.") break elif user_input == "no": print("Thank you for your response.") break else: print("Invalid response. Please try again.")

The output produced by the code is as follows −

Please enter a valid response: hello Invalid response. Please try again. Please enter a valid response: yes Thank you for your response.

Let’s have a look at the step-by-step explanation of the code −

  • Initialize the loop − The first line of the code initiates the «while true» loop.
while True:

As long as the «True» condition is still true, the loop will continue to execute.

  • Prompt the user for input − Within the loop, the following line of code is used to prompt the user for input −
user_input = input("Please enter a valid response: ")

The «input» function is utilized to show the user a prompt and retrieve their input. In this scenario, the prompt is requesting that the user provide a valid response. The answer given by the user is saved in the «user input» variable.

  • Check the input − The code then checks the user’s input to see if it is correct. This is accomplished through the use of an «if» statement.

The «if» statement examines if the «user input» variable is either «yes» or «no». If the user enters «yes,» the code inside the first «if» block is executed, displaying a message thanking the user for their response. If the answer is «no,» the code inside the second «if» block is executed, and another message thanking the user is displayed. If the user’s input is neither «yes» nor «no,» the code inside the «else» block is executed, and an error message indicating that the answer is invalid is displayed.

  • Terminate the loop − The code’s final step is to end the loop if the user provides a valid response. This is accomplished with the «break» statement −
break

The loop is terminated by using the «break» statement. If the user selects «yes» or «no,» which are both acceptable responses, the «break» statement will be carried out, breaking the loop. The loop will continue to run and the user will be prompted for input once more if the user’s response is invalid.

The «while true» loop needs to be broken by an external event, such as a «break» statement. The loop will continue to run until the user quits the program if there is no «break» statement or another way to stop it. If the loop is carrying out an operation that consumes a lot of resources, such as CPU time or memory, this could lead to issues. To prevent this, it is crucial to carefully prepare the circumstances in which the loop should end and incorporate a means of stopping the loop if these circumstances are realized.

Conclusion

In summary, the «while true» loop is an effective tool for repeating tasks up until a predetermined condition is met. This loop structure is a key component of a Python programmer’s toolkit, whether it is used in a simple script or a complex project. You may produce more effective and productive code and confidently take on a variety of programming jobs by becoming an expert at using the «while true» loop.

Python While Loop

Harish Rajora

Enroll in Selenium Training

In the last post about Python «for» loops, we got introduced to Python’s concept and how does Python handle loop. With different variations and methods introduced in loops, we are all set to move ahead to the next and probably the only other important loop in Python: python while loop. Since this is also a loop, the work needs no introduction in this post. If you are unaware, I highly recommend going through the python «for» loops and brief yourselves with the basics.

This post will cover the basics in the following fields:

  • What is the Python «While» loop?
    • Syntax of Python «while» loop.
    • How to implement while loops in Python?
    • Flowchart for Python While loops.
    • While True in Python
    • While-Else in Python
    • Python «Do While» loops.

    What is the Python «While» loop?

    The while loop in python is a way to run a code block until the condition returns true repeatedly. Unlike the «for» loop in python, the while loop does not initialize or increment the variable value automatically. As a programmer, you have to write this explicitly, such as «i = i + 2«. It is necessary to be extra cautious while writing the python «while» loop as these missing statements can lead to an infinite loop in python. For example, if you forgot to increment the value of the variable «i» , the condition «i < x» inside «while» will always return «True«. It is therefore advisable to construct this loop carefully and give it a read after writing.

    The syntax for Python while loops

    The syntax for python while loop is more straightforward than its sister «for» loop. The while loop contains only condition construct and the piece of indented code, which will run repeatedly.

    while(condition): //Code Block 

    How to implement a while loop in Python?

    To implement the while loop in Python, we first need to declare a variable in our code as follows (since initialization is not like the for loop):

    i = 1 

    Now I want «Good Morning» to be printed 5 times. Therefore, the condition block will look as follows:

    The indented code will be the code I would like to execute when the condition returns True.

    print("Good Morning") i = i + 1 

    Combining my code, it will look as follows:

    i = 1 while(i 5): print("Good Morning") i = i + 1 

    When we compile and run the code, the following iterations occur during the loop execution:

    python while loop output

    Can you guess what would happen if I skip the line i = i + 1? Run it and find out!

    If the code block inside the while loop is a single statement, the programmer can also write the while loop. Moreover, the statement in a single line as follows:

    while(condition): Single Statement 

    Flowchart for Python While loops

    Now that we know the working and construction of the while loop, we can visualize the loop’s flow through a flowchart. The flowchart of python «while» loop would look as follows:

    flowchart of while loop in Python

    I hope it comes in handy while practicing for the “while” loop in python.

    While True in Python

    There is a concept of declaring a condition true in python or any other programming language without evaluating any expression. It is a practice followed to indicate that the loop has to run until it breaks. We then write the break statements inside the code block.

    The while true in python is simple to implement. Instead of declaring any variable, applying conditions, and then incrementing them, write true inside the conditional brackets.

    while(True): //code block 

    The following code will run infinitely because «True» is always «True» (no pun intended!).

    while(True): print("Good Morning") 

    Use this condition carefully as if your break statement is never touched. Your loop will continuously eat the resources and waste time. Typically, while true in python is used with a nested if-else block, but this is not standard, and there is no such rule. Every program has its demands, and as you work your way forward, you will be able to implement this with variations. I have shown a program to implement in the snippet below while true in python with a sure path of exit.

    weekSalary = 0 dayOfWeek = 1 week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] while(True): if(week[dayOfWeek] == "Sunday"): print("Week Over, Its holiday!!") break weekSalary += 2000 dayOfWeek += 1 print(str(weekSalary)) 

    Can you think out the output of this code using the iteration process?

    while true in python

    The example above uses python lists and breaks statements in the code. Please refer to python lists and break statements in python to learn more about them.

    While-Else in Python

    The while loop in python also supports another interesting use case. If there are any program requirements to execute a sentence after the loop, we can construct an «else» statement that would execute when the condition returns «False.» After the «else» statement, the loop exits.

    while(condition): //code block else: //code block 

    A small example to demonstrate the same is as below:

    i = 2 while(i 3): print("i is less than three") i = i + 1 else: print("i is now greater than three") 

    The above code prints the following output onto the console:

    while_else_python

    Alright! A good question to think here is, what happens when we have a break statement along with the else statement? Do else statements get skipped? Or does «else» get executed?

    If there is a while loop in python with a break statement and an else statement, the else statement skips when the»break» executes. It would be a good exercise to run a while loop in Python with a break and else statement.

    You can also implement the for-else statement in the for loop, and it works exactly as same as here. The following syntax will help you build your for-else loop in the code:

    for(conditions): //code else: //code 

    Please visit the for loop in the python section to learn more about the for loops.

    Python «do while» loop

    In case you are coming from another programming language such as C++, you might have used a «do while» loop and would be interested in knowing how to implement the same in python. Unfortunately, for «do while» fans, this loop is not supported by python. I feel the «do while» loop is redundant as it is similar to the «while» loop except for the first iteration, which is bound to run necessarily in «do-while

    Leaving the standard textbook facts aside, can you try to build a do-while loop in python by yourself? The «do-while» loop always executes the first iteration and then checks the condition to decide if another iteration would run or not. To understand it using another loop, let’s dissect this statement and construct a «do-while» loop ourselves.

    Statement 1: The «do-while» loop always executes the first iteration.

    This statement tells us that we do not need to check the condition while entering the code block. Does that ring any bells? Yes. we need a «while true» statement since it is always true. So we start with the following statement:

    while (True): 

    Statement 2: After that, check the condition to decide if another iteration would run or not.

    Since we need to check the condition after the code block has executed once, we can put a simple if statement with a break as follows:

    while(True): //Code Blocks if(condition): break 

    The above code works exactly similar to the following do-while loop:

    do < //code block > while(condition); 

    It brings us to the end of this post. I hope we addressed all your queries in this post. If some doubt remains, you can raise them in the FAQ section or email me at [email protected]. I would be happy to help you out!

    Key Takeaways

    • The while loop in python runs until the «while» condition is satisfied.
    • The «while true» loop in python runs without any conditions until the break statement executes inside the loop.
    • To run a statement if a python while loop fails, the programmer can implement a python «while» with else loop.
    • Python does not support the «do while» loop. Although we can implement this loop using other loops easily.

    Что такое True в цикле while(while True:)?

    Здравствуйте! Да, это может показаться глупым, но я всё ещё не знаю, что такое True в цикле while(while True! Может быть это какой-то аргумент. Я не знаю, по этому данная тема и была создана! Очень хочу про это узнать!
    Заранее спасибо!

    Лучшие ответы ( 1 )
    94731 / 64177 / 26122
    Регистрация: 12.04.2006
    Сообщений: 116,782
    Ответы с готовыми решениями:

    Свойства контрола webbrowser: addressbar:true, statusbar:true, menubar:true
    Я чайник, конечно, но. решил и я свой броузер написать 🙂 Беру контрол webbrouser, кидаю его на.

    Что такое: W1030 Invalid compiler directive: ‘true’?
    При компиляции выдает предупреждение — Warning. Вот его содержимое: W1030 Invalid compiler.

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

    8739 / 5779 / 2317
    Регистрация: 21.01.2014
    Сообщений: 24,745
    Записей в блоге: 3

    Лучший ответ

    Сообщение было отмечено Give как решение

    Решение

    Данная конструкция служит для организации бесконечного цикла. Вообще, если Вам знаком синтаксис оператора цикла while — вопрос возникнуть не должен был:

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

    что такое в данном контексте условие? Это логическое выражение, результатом которого будет являться или Истина (True) или Ложь (False) Блок инструкций будет выполняться, пока условие истинно. Для того, чтобы цикл не стал бесконечным, внутри блока инструкций должны быть предприняты какие-либо действия, чтобы условие изменило свой знак, например, изменение значения переменной, которая в условии сравнивается с какой-либо величиной.
    В Вашем случае условия, как такового, нет, оно заменено константой, поэтому изменения этой константы внутри блока инструкций не происходит и цикл становится бесконечным. Естественно, чтобы не завесить систему, внутри блока инструкций таки, должно быть условие, при выполнении которого произойдет выход из цикла иначе это бессмысленная конструкция.

    87844 / 49110 / 22898
    Регистрация: 17.06.2006
    Сообщений: 92,604
    Помогаю со студенческими работами здесь

    Xsi:nil=»true» Что это такое?
    Здравствуйте уважаемые форумчане, мне нужно сформировать xml для saop. Web service мне.

    Что такое в jquery и java return false и return true
    Если я правильно понимаю, то return false отменяет действие по умолчанию, например клик по ссылке.

    Значение true в цикле while
    Что из себя представляет это true в while. Я понимаю, что пока условие верно в <>, но хотелось.

    define true false; AllowNoPassword=true
    Добрый день! Разворачиваю новую рабочую площадку на новом компе. Установил LAMP — все.

    Кто может объяснить смысл цикла While True в Python?

    Как можно понять что значит While True: . ? Я только понял, что цикл будет в таком случае бесконечным до тех пор, пока я не пропишу команду break, но в чём смысл самого выражения While True? И есть ли выход из такого цикла без break, например если «что-то» станет False 😀 Может вопрос тупой, но спасибо тому, кто ответит 😀

    Отслеживать
    задан 4 июл 2020 в 20:54
    Никита Смирнов Никита Смирнов
    81 1 1 золотой знак 2 2 серебряных знака 9 9 бронзовых знаков
    What does “while True” mean in Python? stackoverflow.com/questions/3754620/…
    4 июл 2020 в 21:07
    Спасибо! 123123
    4 июл 2020 в 21:16

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

    4 июл 2020 в 21:19
    Выход из такого цикла возможен при исключении, при завершении нити или процесса.
    22 авг 2022 в 6:40

    3 ответа 3

    Сортировка: Сброс на вариант по умолчанию

    Типичная ситуация для использования подобного цикла, это когда условие завершения становится известно только в середине итерации.

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

    total = 1 while True: x = int(input()) if x == 0: break total *= x print(total) 

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

    total = 1 x = int(input()) while x != 0: total *= x x = int(input()) print(total) 

    Но в таком случае программа перестает удовлетворять т.н. принципу DRY.

    В python 3.8 появилась новая конструкция, которая позволит избавиться от while True в подобных случаях

    total = 1 while (x := int(input())) != 0: total *= x print(total) 

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

    Кроме того, не стоит забывать о том, что некоторые циклы могут быть безусловно бесконечными, и в таких случаях без while True не обойтись

    def count(x): while True: yield x x += 1 for z in count(1): for y in range(1, z + 1): for x in range(1, y + 1): if x**2 + y**2 == z**2: print(f'**2 + **2 == **2') 

    Отслеживать
    ответ дан 4 июл 2020 в 23:20
    10.8k 2 2 золотых знака 16 16 серебряных знаков 36 36 бронзовых знаков

    Это означает что цикл является постоянно истинной. То есть пока правда==правда выполнять. Можно без брейка, но тогда вместо True надо будет использовать булевую переменную которая будет равна истине. Например:

    a = True while a: #Цикл a = False 

    (Отвечаю с телефона, сорян)

    Отслеживать
    25.9k 7 7 золотых знаков 31 31 серебряный знак 48 48 бронзовых знаков
    ответ дан 4 июл 2020 в 21:02
    11 3 3 бронзовых знака

    Понял, прошёл ещё по ссылке комментария на мой вопрос. Получается из такого цикла без break выхода нет 🙂

    4 июл 2020 в 21:15
    Ну да, выхода нет. Рад что помог
    4 июл 2020 в 21:24
    4 июл 2020 в 21:57
    Что-то не открылось
    5 июл 2020 в 22:05

    Гениально ответил человек по ссылке: это то же самое, что сказать While (6>5), что по сути While True и есть. Бесконечный цикл, ибо правда всегда правда 😀 Там каждая строчка ответа очень интересная и понятная поэтому прикреплю его ответ сюда, чтобы прочитали потом те, кому интересно:

    Everything inside the () of the while statement is going to be evaluated as a boolean. Meaning it gets converted into either true or false.

    Consider in the statement while(6 > 5)

    It first evaluates the expression 6 > 5 which is true so is the same as saying while(true)

    Anything that is not FALSE, 0, an emptry string «», null, or undefined is likely to be evaluated to true.

    When I first started programming I used to do things like if(foo == true), I didn’t realise that was virtually the same thing as if(foo).

    So when you say while(true) its like are saying while(true == true)

    So to answer you question: While TRUE is True.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *