while swag: will run while swag is "truthy", which it will be while swag is True, and will not be when you set swag to False.

Answer from Xymostech on Stack Overflow
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-while.html
While Loop
While Operation: Check the boolean test expression, if it is True, run all the "body" lines inside the loop from top to bottom. Then loop back to the top, check the test again, and so on.
Discussions

Can You Break A While Loop Via Return Boolean Value From A Function?
You're all fantastic, I love you. Muah muah. More on reddit.com
๐ŸŒ r/learnpython
14
6
May 21, 2022
need help understanding Boolean statement in while loop
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. More on reddit.com
๐ŸŒ r/learnpython
13
1
December 24, 2018
๐ŸŒ
Kansas State University
textbooks.cs.ksu.edu โ€บ intro-python โ€บ 05-loops โ€บ 02-while-loops
While Loops :: Introduction to Python
June 27, 2024 - Resources Slides The first type of loop to explore in Python is the while loop. A while loop uses a Boolean expression, and will repeat the code inside of the loop as long as the Boolean expression evaluates to True. These loops are typically used when we want to repeat some steps, but we arenโ€™t ...
๐ŸŒ
Projectpython
projectpython.net โ€บ chapter03
ProjPython โ€“ Loops and conditions - Project Python
The < sign is called a conditional operator, and it takes two values and produces a boolean True or False value. For example, 3 < 4 evaluates to True, and 4 < 3 evaluates to False. So i < 6 evaluates to True if and only if the value in i is less than 6. One major use of conditional operators ...
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ while boolean python | example code
While Boolean Python | Example code - Tutorial - By EyeHunts
July 21, 2021 - Python While loop uses the Boolean value to executes the loop body while the expression evaluates to (boolean) โ€œtrueโ€. You can use a variable as a condition for your while loop instead of just while True.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_booleans.asp
Python Booleans
You can create functions that returns a Boolean Value: ... Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type:
๐ŸŒ
Tutorial Teacher
tutorialsteacher.com โ€บ python โ€บ python-while-loop
Python while Loop
Python uses the while and for keywords to constitute a conditional loop, by which repeated execution of a block of statements is done until the specified boolean expression is true.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ can you break a while loop via return boolean value from a function?
r/learnpython on Reddit: Can You Break A While Loop Via Return Boolean Value From A Function?
May 21, 2022 -

I feel like it should work, but Python doesn't seem to care about my feelings. So I'm playing around with functions and I feel like I should be able to create a function that returns a boolean value that breaks a while loop in the body of the code. So here's what I've got, sadly, it doesn't seem to actually read what's being returned and just continues to ask for a username. Please, ignore my stupid usernames, I am neither smart no clever. :

def username_checker(username, users,):
    """Checks list of users to find out if username is already taken"""
    if username in users:
        print("\nSorry that name is already taken.")
        return True

    else:
        print (f"\nWelcome, {username}")
        return False
        

users = ["bbrad", "poopinajimmyhat7", "coolkid28",]
while True:
    user_name = input ("\nPlease enter a username: ")
    username_checker (user_name, users)
๐ŸŒ
Cherry Servers
cherryservers.com โ€บ home โ€บ blog โ€บ python โ€บ how to use a boolean in python? (with examples)
How to Use a Boolean in Python? (With Examples) | Cherry Servers
November 7, 2025 - In this example, "number < 5" is the boolean expression controlling the loop. The loop keeps running as long as this expression evaluates to True. Once the number reaches 5, the expression evaluates to False, ending the loop. ... While "for" loops in Python typically iterate over a sequence ...
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ fopp โ€บ MoreAboutIteration โ€บ ThewhileStatement.html
14.2. The while Statement โ€” Foundations of Python Programming
For example, the program in the previous section could be rewritten using while. Instead of relying on the range function to produce the numbers for our summation, we will need to produce them ourselves. To do this, we will create a variable called aNumber and initialize it to 1, the first number in the summation. Every iteration will add aNumber to the running total until all the values have been used. In order to control the iteration, we must create a boolean expression that evaluates to True as long as we want to keep adding values to our running total.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ value-true
Python True: Understanding Boolean Values | Learn Python
In a Python while loop, a condition needs to be True for the loop to continue or execute in the first place. At some point, however, the condition needs to become False, or the loop needs to trigger a break statement. If the condition always evaluates to True, the loop becomes infinite ("infinite ...
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ while-loops-in-python-while-true-loop-statement-example
While Loops in Python โ€“ While True Loop Statement Example
July 19, 2022 - The general syntax for writing a while loop in Python looks like this: while condition: body of while loop containing code that does something ... You start the while loop by using the while keyword. Then, you add a condition which will be a Boolean expression.
๐ŸŒ
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.
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-boolean.html
Boolean Expressions
The operation of the if-statement and while-loop is based on bool values, but works in a slightly more flexible way. See Truthy Logic for details. Boolean values can be combined with the operators and or not, like following (printing 'yay' if x is greater than 0, but not 5 : ... Python is unique in using the plain words like "and" for this.
๐ŸŒ
Python
pythonprogramminglanguage.com โ€บ while-loop
While Loops (iteration) Explained - Python
The expression <exp> is evaluated in Boolean context. If the expression <expr> is True, the loops body is executed. While it stays True, it keeps repeating. If the expression <expr> becomes False, it ends the loop. ... Because if a is equal to 6, the condition i < 6 is False.
๐ŸŒ
TOOLSQA
toolsqa.com โ€บ python โ€บ python-while-loop
Python While Loop | While True and While Else in Python || ToolsQA
August 6, 2021 - 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. ... The conditions can be as simple as (i < 5) or a combination of them with the boolean operators' ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-while-loop
Python While Loop - GeeksforGeeks
Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.
Published ย  December 23, 2025
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-use-while-true-in-python
How to use while True in Python - GeeksforGeeks
May 27, 2025 - In Python, loops allow you to repeat code blocks. The while loop runs as long as a given condition is true. Using while True creates an infinite loop that runs endlessly until stopped by a break statement or an external interruption.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ booleans
Python Booleans: Essential Logic for Coding Success
Booleans continue the loop while a condition evaluates to True and terminate the loop when the condition becomes False. ... In Python, boolean values represent the truth of an expression. Logical operations with boolean operators allow you to combine, invert, or compare expressions.
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ python while loop
Python while Loop - AskPython
February 16, 2023 - We can define an object boolean value by implementing __bool__() function. We use the reserved keyword โ€“ while โ€“ to implement the while loop in Python.