while will always evaluate whatever comes behind it. For instance i =0 while i < 10: print(i) i = i+ 1 Here i <10 is evaluated to either be true or false. This will happen each iteration. i = 0 , True i= 1, True i= 2, True Etc, untill: i=10, False => break loop The code will continue untill it evaluates to false. while True kind of hacks it: True will always evaluate to True. While looks at it and thinks: hey this is true! So it always continues. While true isn't commonly used, but when it is it's commonly used with a break statement. (Or interrupted by ctrl + c). While False will never do anything in the loop as you stated. It checks to see if False is True. But it's never true, so it doesnt execute the code in the while loop. (Sorry fod bas formatting, mobile) Answer from Zer0designs on reddit.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ sorry to ask such a silly question but what does 'while true:' actually mean?
r/learnpython on Reddit: sorry to ask such a silly question but what does 'while True:' actually mean?
November 14, 2023 -

what does the True refer to?

eg if i write:

while True: 
    print("hi")

i know that "hi" will be repeated infinitely, but what is it thats True thats making "hi" get printed?

also, whatever it is thats True, im assuming its always true, so is that why if i typed 'while False', none of the code below would ever run?

sorry if this is a stupid question

edit: also, besides adding an if statement, is there anything else that would break this infinite while loop?

and how would i break the loop, lets say after "hi" has been printed 10 times, using an if statement or whatever else there is that can break it. thanks!

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how do while not loops work
r/learnpython on Reddit: How do while not loops work
September 11, 2024 -

I was reading through this code and I'm just not getting how while loops work when not operator is also used.

https://pastebin.com/5mfBhQSb

I thought the not operator just inversed whatever the value was but I just can't see this code working if that's the case.

For example , the while not sequenceCorrect should turn the original value of False to True, so the loop should run while it's True. But why not just state while True then? And why declare sequenceCorrect = True again? Doesn't it just means while True, make it True? And so on.

The only way it makes sense to me is of the while not loop always means False (just like the while always means as long as it's True) even if the value is supposed be False and should be inverted to True.

So, is that the case? Can anyone explain why it works like that?

Top answer
1 of 8
7
In general, recall the while loop syntax. while : Conceptually, coding aside, consider filling a glass of water. Is there space for more water in the glass? Okay, then pour some. Without going in detail of how this funky glass object is defined, hopefully the following makes sense as a python analog of that process. while glass.has_space(): #we're still filling the glass glass.add_water() #glass is now full of water Without writing out how this glass object works, let's say it has another method for returning a boolean (True/False) for whether or not it is currently full, instead of the previous example of whether or not it had space for more water. We can fill the glass in the same way, but we have to negate that statement using the not operator while not glass.is_full(): #we're still filling the glass glass.add_water() #glass is now full of water Going back to the initial syntax, which is still the same, the only thing we've done is changing the condition statement of the loop. Instead of checking that glass.has_space() evaluates to True, we are now checking that the expression not glass.is_full() evaluates to True. That is the same statement as evaluating that glass.is_full() evaluates to False, because the only thing the not operator does to a boolean is negating it, i.e. True becomes False and vice versa. Now looking at your code linked, the condition for looping is that not sequenceCorrect evaluates to True, which is equivalent to the statement that sequenceCorrect is False. I won't paste the code here, but we see on line 3 that sequenceCorrect starts its life being False, so upon entering the while loop we do indeed step into that block of code because at that time not sequenceCorrect is in fact True. Then the first thing we do on line 5 is reassign it to True. If the remaining lines don't change it back to False, this will stop the while loop from repeating, since in this current state not sequenceCorrect evaluates to False. So you can say that line 5 is defaulting the loop to not going to be repeated. The only way for the loop to be repeated is for lines 6-8 with the nested for loop and if statement to find some character in dna that is not in "actgn", upon which sequenceCorrect will be assigned to False and thus the statement in the while loop not sequenceCorrect would evaluate to True and thus the loop would repeat itself once more. Personally, I think this is just a pretty unclear way to achieve the goal of checking the validity of that input string. I would have defined it another way, but I can't see anything wrong with it really. If the not operation in the while loop statement is bothering you, you could equally have rewritten the code with a variable for instance named sequenceIncorrect and just flipped all assignments i.e. True's become False's and vice versa.
2 of 8
2
The difference here is that by using not sequenceCorrect you are avoiding the use of the break keyword. It's cleaner and makes the loop terminate itself, rather than relying on a specific keyword and force terminate it. You could use while True, but that way is not descriptive enough and can potentially create and endless loop if you don't take care of the edge cases. Think about it: while not sequenceCorrect is telling you, without a single comment line, that the loop should run while sequenceCorrect is False, vs while True which the only thing that's telling you is that this loop will run endlessly for unknown reasons.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ help understand while true/while false
r/learnpython on Reddit: Help understand while True/while False
December 19, 2015 -

for example, why does this code work:

user = input("Enter marital status: ")
user = user.upper()
valid = False
while not valid:
    if user == "M" or user == "S":
        valid = True
    else:
        print ("invalid input")
        user = input("Enter marital status: ")
        user = user.upper()

but this doesn't:

user = input("Enter marital status: ")
user = user.upper()
valid = True
while not valid:
    if user == "M" or user == "S":
        valid = False
    else:
        print ("invalid input")
        user = input("Enter marital status: ")
        user = user.upper()

isn't the boolean condition changing in both cases?

can someone just give me some guidelines for using while True/False,e.g. when is it best to use this type of a while loop? that I can follow on my test tomorrow (yes, tomorrow).

Thanks in advance!

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ trouble understanding while not
r/learnpython on Reddit: Trouble understanding While Not
February 16, 2017 -

I'm doing "automate the boring stuff" and was on an early lesson about while loops. I can't wrap my head around "while not." The code is below

name = ''
while not name:
     print('Enter your name:')
     name = input()
print('How many guests will you have?')

While my limited knowledge, I would write it instead as

name = ''
while name == '':
    print('Enter your name:')
    name = input()
print('How many guests will you have?')

My question is how can they mean the same thing? Both start with name = False/empty. The way I interpret the top code is, while name is not False/empty. The way I interpret the bottom is, while name is equal to False/empty. In my mind, the top would keep looping with any True value. Thanks for your help!

EDIT: formatting

EDIT 2: Finally figured it out. I'm posting this edit for prosperity sake, for any other programming ogres like me. As long as the condition line is True, the loop will run. If the condition is False, the loop will not run. Even though name is False, the condition line is True and the loop will go until something is inputted. Once something is typed in, name becomes True, which would make the condition not name False, ending the loop.

Thanks everyone for helping me understand that! It's so simple now that I see it. I'm super new to Python and made a rookie mistake.

๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ while true antipattern
r/Python on Reddit: While True Antipattern
July 31, 2022 -

I'm working on designing an application, and the high level intention is to run the app forever; Sort of like a Daemon service. The only way I can think of doing this is

  1. While True:

  2. Decorator that does the While True: forever.

This really feels like an anti-pattern to me. What are some other ways to keep an app running forever?

Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/programminghorror โ€บ convince me to not use "do { ... } while (false);"
r/programminghorror on Reddit: Convince me to not use "do { ... } while (false);"
October 26, 2023 -

I love this pattern:

do {
    something();
    if (condition) {
        break;
    }
    somethingelse();
    ....  // yadda yadda
} while (false);

I think it is beautiful. It is brilliant. Once you get it (it should not take long), you just have to agree that it makes code a lot easier to read.

Yet people online seem to disagree with this pattern. They claim "it is just a structured goto". But I disagree. It is fundamentally different from a goto. In a goto, you never know where you'll end up after following the label name. This is not the case here. You know exactly where you will land, and hence there is absolutely no spaghettification.

The code is much cleaner this way - everybody hates nested ifs.

Try to change my view, but I think you can't.

Top answer
1 of 5
124
unless you've got additional metrics to show it is noticeably inefficient to do so, I'd probably argue that this example would be more suitable as a separate function where you just return out of it when you do not need to continue. The argument against what you are doing is that it requires you to read the entire block from the start to the end to realise it isn't actually ever going to loop more than once, which can be misleading/increase the cognitive complexity of this code block. If you need complicated control flow and are not micro-optimising, then it is often a sign you should break up your problem into smaller chunks. Code should be readable, boring, and explicit. Doing stuff in a "smart" way without physical evidence that it is required to prevent a noticeable defect in the final product, or maintainability, is almost never a good idea and just makes the codebase into a pain to work with over time. I'd rather something be verbose and boring than smart and confusing for the sake of a few lines of code.
2 of 5
43
The lengths people will take to avoid using goto when thatโ€™s what they actually mean, just because some Dutch dude said that only naughty programmers use goto. The problem I have with this is that when I see do, I assume Iโ€™m looking at a loop. I have to read all the way to the end to find out that itโ€™s not a loop at all. And then, if I donโ€™t already know the trick, I have to pause for a second to figure out whatโ€™s going on. As others have said, function with early return is clearer. Use a local function if you want to keep the logic together in one place.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ can someone explain what this `while true` function is actually checking?
r/learnpython on Reddit: Can someone explain what this `while True` function is actually checking?
December 13, 2023 -

https://pastebin.com/NWkKQc1P

It's from Automate the Boring Stuff. I tried running it through the python tutor and it didn't clarify. Is the basic point that there actually isn't anything it's checking to be True, so it's an infinite loop until you trigger the `break`?

PS I figure this is something simple from much earlier that I didn't internalize. I plan to go through all the basic curriculum again to make sure there aren't any gaps in super basic knowledge.

Top answer
1 of 8
23
A while loop runs while a condition is true. True is always true, so it will run until something causes it to break (e.g. a break statement, program crash, etc.) For comparison, the first loop in the code you posted could be rewritten without an infinite loop as: age = input("Enter your age: ") while not age.isdecimal(): age = input("Please enter a number for your age: ")
2 of 8
9
Correct; this is just a way to start an infinite loop that you intend to break with some condition/break statement later on. Mostly used for starting/running an application that you don't want to close down without user intent (clicking an exit/quit button in a UI or entering "quit", "exit", etc from the command line. It *isn't* a great construct to use when you want something that has solidly defined criteria to repeat until those criteria are met. As mopslik pointed out, you would be better served in those examples to actually use the defined criteria in those as your loop conditions since you're not at risk of just sticking the user in an infinite loop if you forget to write your break statement somewhere. You, also, don't have to write so many lines to accomplish the same goal. ``` password = "" while not password.isalnum(): password = input('Select a new password (alphanumeric only') print("Password is good") ``` You do not have to print a line and then call input(), either. Just put the message you want displayed into the parens for the function call: input("Enter your age: ")
๐ŸŒ
Reddit
reddit.com โ€บ r โ€บ learnpython โ€บ comments โ€บ kueepr โ€บ what_does_while_true_mean
What does "while True" mean? : r/learnpython
January 10, 2021 - Subreddit for posting questions and asking for general advice about all topics related to learning python.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ none object and while loop confusion.
r/learnpython on Reddit: None object and While loop confusion.
June 23, 2022 -
Player_1 = None

While (not Player_1):
    Player_1 = input('your name')

I'm not new to python, I understand classes and functions etc..but this is really baffling me and I need some help understanding 'None' and the While loop.

I understand that 'not' negates a Boolean value, I get that piece, but None is not a Boolean value, I've searched this and None is its own Object and None is also not equal to False or True.

The while loop runs if the condition evaluates to true, and doesn't run if evaluated to False.

What is making the loop run the first time and not the second time. Obviously, the first time the logic equates to True and the second time to False...But I don't get the logic.

I think it's the "not" which is confusing me, what is the not doing?

Can someone please enlighten me?

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ while true loops vs try except
r/learnpython on Reddit: While True loops vs Try Except
May 11, 2024 - while True: try: value = float(input("Enter a float: ")) except ValueError: print("No good.") else: break ... Like mopsilk and qazbarf have pointed out, you're thinking about this a bit wrong. Raising exceptions is the standard way Python code can signal an error.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ help with python program where an inputted number is "true" or "false" (true if even, false if odd)
r/learnprogramming on Reddit: help with python program where an inputted number is "true" or "false" (true if even, false if odd)
February 11, 2025 -

Hi, I was coding a program (description in title). I just learnt about using functions, and was wondering why line 4 and line 6 can't be used in such a way. I know that I can just 'return' true or false, but was curious on why this method is unacceptable.

Any help or suggestions are appreciated!!

x = int(input ("What is your number? "))
def is_even (x):
    if x % 2 == 0:
        is_even(x) == "true"
    else:
        is_even(x) == "false"

print (f"It is {is_even(x)} that your number is even")
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ what's the difference between using the break keyword and using the false keyword to exit a while loop?
r/learnpython on Reddit: What's the difference between using the break keyword and using the False keyword to exit a while loop?
May 19, 2018 -

Using break: https://repl.it/repls/SinfulMonstrousProperties

Using False: https://repl.it/repls/MildMulticoloredCases

I am learning about this flag. If you use the False keyword, you can exit the while loop whenever the elif statement = False.

What's the difference between this and just using the break keyword.

EDIT:

break ends your loop right now, whereas setting some flag equal to False means you're going to execute any remaining code in your current iteration of the loop.

Thank you guys so much for your help. r/learnpython is MUCH better than r/javahelp!

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ need help understanding boolean statement in while loop
r/learnpython on Reddit: need help understanding Boolean statement in while loop
December 24, 2018 -

Hello I am doing Jose Portillas course on python in udemy and I ran into a bit of code that I am having a hard time wrapping my head around.

def summer_69(arr):
    sum69 = 0 
    cond = True
    for num in arr:
        while cond: 
            if num != 6: 
                sum69 += num
                break
            else: 
                cond = False
        while not cond: 
            if num != 9: 
                break
            else:
                cond = True
                break
summer_69([2, 1, 6, 9, 11])

as you can see the variable cond starts with True assigned to it. but in the first while loop if the condition is no longer met (that the variable num is not equal to 6) then the cond will have its value reassigned to False.

so if cond is now false. how come it skips the first while loop considering that the while loops condition is met in the next iteration

and also why, in the second while loop, does it meet the conditions is the variable assigned to cond somehow still True?

Top answer
1 of 3
4
For your first question: cond is initalized (and set to True) before the for-loop, so if it get changed inside the iteration (doesn't matter if inside the while-loop or anywhere else inside the iteration), it stays changed, until a next iteration changes it again or it gets changed after the for-loop is done. So, if a iteration changes cond to False, with the next iteration cond is still False and therefore it skips the first while-loop. Example step by step with arr = [2, 6, 7, 9]: sum69 = 0 cond = True (iteration 1) num = 2 # entering first while-loop, because cond=True # entering if-statement because 2 != 6 sum69 = 2 # entering next iteration because of break (iteration 2) num = 6 # entering first while-loop, because nothing changed with cond # ignoring if-statement because 6 == 6 # entering else cond = False # entering second while-loop # entering if-statement because 6 != 9 # entering next iteration because of break (iteration 3) num = 7 # ignoring first while-loop because cond changed in the last iteration # entering second while-loop # entering if-statement because 7 != 9 # next iteration because of break (iteration 4) num = 9 # ignoring first while-loop because cond changed in iteration 2 # ignoring if-statement because 9 == 9 # entering else cond = True # next iteration because of break (now it would work again like in iteration 1) # end of function I don't exactly understand the second question.
2 of 3
3
This was code used as an example in a course that's teaching python? This is just my personal opinion, but there's no reason that the code needs to be this obfuscated. And just at a glance, if this is the quality of code being written for examples, that would lead me to believe the course is probably not teaching you best practices. I cleaned up the code to get rid of all the while loops and breaks, and also added a return so the function actually does something. Currently it just throws away the result when the function returns. def summer_69(arr): sum = 0 cond = True for num in arr: if cond: if num == 6: cond = False else: sum += num else: if num == 9: cond = True return sum That should be a bit easier to follow along without getting too far away from what the original code (and I'm pretty sure this could be further improved). In short, this function iterates through a list of numbers and keeps a running total of all the numbers until it finds a 6. After it finds a 6, it stops adding any numbers to the total until it finds a 9. Then it resumes adding those subsequent numbers to the total. Think of 6 as an off switch and 9 an the on switch, with the function starting in the on position. I don't blame you for having difficulty understanding what the original code was doing. Both the inner while loops were unnecessary and by extension so were the breaks. Also the if statements were all screwy. The instructor was thinking about them backwards. When a number is 6 or 9, that has special meaning so it should be clear that those are what flip the boolean. Those shouldn't be on an else block when a number isn't 6 or 9. Doing it that way hides the intent.