Difference between while not __ and while __ == false ? (python) - python

I am trying to distinguish between different ways of writing while loops.
I am writing this specifically for a poker game where I distinguish between different hand types. When writing my is_pair function, I start by saying pair = False. The only way I have found that continues the loop is if I say while pair == False: .... For my is_flush function I am able to set flush = True and the while loop runs on while flush which continues the loop until flush is not true any more.
I have tried while not pair: but that didn't work. I want it to continue while pair is False so when it has found a pair it will return as True.
I think the statement for flush just looks cleaner and I am wondering if there is another way to incorporate that style into my pair function.

Since your while not pair: loop did not work, you have found an important difference: pair == False only tests true if pair is set to 0 or False (the only two values that test as equal to False), while while not pair tests for any truth value (inverting that value).
You appear to have assigned some other value to pair that is neither of those two values causing the behaviour to change (a truthy value to break out early, or a falsey value to keep the loop going longer than expected).
It is that difference that is one of the reasons why the Python style guide recommends you always use if true_expression or if not false_expression rather than use == True or == False:
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
Last but not least, for a while ...: loop that simply tests against a single boolean flag (while flag: or while not pair:), consider using while True: and break instead. So rather than do:
flag = True
while flag:
# ...
if condition:
flag = False
do this instead:
while True:
# ...
if condition:
break

Aside from actually having little or no difference at all,
Using False in a == comparison allows usage of 0 and 1.
0 == False
1 == True
Using not is inversion of current value.
not 0 == True
not 1 == False
not False == True
You can use in your program assuming that pair can only contain boolean values:
while not pair:
If you however still want to use a variable that can contain both boolean and number, you can use:
while pair is False:

Related

a simple "Hello" prints like "hellohellohellohello" in python socket [duplicate]

def play_game(word_list):
hand = deal_hand(HAND_SIZE) # random init
while True:
cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
if cmd == 'n':
hand = deal_hand(HAND_SIZE)
play_hand(hand.copy(), word_list)
print
elif cmd == 'r':
play_hand(hand.copy(), word_list)
print
elif cmd == 'e':
break
else:
print "Invalid command."
While WHAT is True?
I reckon saying 'while true' is shorthand, but for what? While the variable 'hand' is being assigned a value? And what if the variable 'hand' is not being assigned a value?
while True means loop forever. The while statement takes an expression and executes the loop body while the expression evaluates to (boolean) "true". True always evaluates to boolean "true" and thus executes the loop body indefinitely. It's an idiom that you'll just get used to eventually! Most languages you're likely to encounter have equivalent idioms.
Note that most languages usually have some mechanism for breaking out of the loop early. In the case of Python it's the break statement in the cmd == 'e' case of the sample in your question.
my question: while WHAT is True?
While True is True.
The while loop will run as long as the conditional expression evaluates to True.
Since True always evaluates to True, the loop will run indefinitely, until something within the loop returns or breaks.
while True is true -- ie always. This is an infinite loop
Note the important distinction here between True which is a keyword in the language denoting a constant value of a particular type, and 'true' which is a mathematical concept.
my question: while WHAT is 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.
In this context, I suppose it could be interpreted as
do
...
while cmd != 'e'
True is always True, so while True will loop forever.
The while keyword takes an expression, and loops while the expression is true. True is an expression that is always true.
As a possibly clarifying example, consider the following:
a = 1
result = a == 1
Here, a == 1 will return True, and hence put True into result. Hence,
a = 1
while a == 1:
...
is equivalent to:
while True:
...
provided you don't alter the value of a inside the while loop.
Formally, True is a Python built-in constant of bool type.
You can use Boolean operations on bool types (at the interactive python prompt for example) and convert numbers into bool types:
>>> print not True
False
>>> print not False
True
>>> print True or False
True
>>> print True and False
False
>>> a=bool(9)
>>> print a
True
>>> b=bool(0)
>>> print b
False
>>> b=bool(0.000000000000000000000000000000000001)
>>> print b
True
And there are "gotcha's" potentially with what you see and what the Python compiler sees:
>>> n=0
>>> print bool(n)
False
>>> n='0'
>>> print bool(n)
True
>>> n=0.0
>>> print bool(n)
False
>>> n="0.0"
>>> print bool(n)
True
As a hint of how Python stores bool types internally, you can cast bool types to integers and True will come out to be 1 and False 0:
>>> print True+0
1
>>> print True+1
2
>>> print False+0
0
>>> print False+1
1
In fact, Python bool type is a subclass of Python's int type:
>>> type(True)
<type 'bool'>
>>> isinstance(True, int)
True
The more important part of your question is "What is while True?" is 'what is True', and an important corollary: What is false?
First, for every language you are learning, learn what the language considers 'truthy' and 'falsey'. Python considers Truth slightly differently than Perl Truth for example. Other languages have slightly different concepts of true / false. Know what your language considers to be True and False for different operations and flow control to avoid many headaches later!
There are many algorithms where you want to process something until you find what you are looking for. Hence the infinite loop or indefinite loop. Each language tend to have its own idiom for these constructs. Here are common C infinite loops, which also work for Perl:
for(;;) { /* loop until break */ }
/* or */
while (1) {
return if (function(arg) > 3);
}
The while True: form is common in Python for indefinite loops with some way of breaking out of the loop. Learn Python flow control to understand how you break out of while True loops. Unlike most languages, for example, Python can have an else clause on a loop. There is an example in the last link.
A while loop takes a conditional argument (meaning something that is generally either true or false, or can be interpreted as such), and only executes while the condition yields True.
As for while True? Well, the simplest true conditional is True itself! So this is an infinite loop, usually good in a game that requires lots of looping. (More common from my perspective, though, is to set some sort of "done" variable to false and then making that true to end the game, and the loop would look more like while not done: or whatever.)
While most of these answers are correct to varying degrees, none of them are as succinct as I would like.
Put simply, using while True: is just a way of running a loop that will continue to run until you explicitly break out of it using break or return. Since True will always evaluate to True, you have to force the loop to end when you want it to.
while True:
# do stuff
if some_condition:
break
# do more stuff - code here WILL NOT execute when `if some_condition:` evaluates to True
While normally a loop would be set to run until the while condition is false, or it reaches a predefined end point:
do_next = True
while do_next:
# do stuff
if some_condition:
do_next = False
# do more stuff - code here WILL execute even when `if some_condition:` evaluates to True
Those two code chunks effectively do the same thing
If the condition your loop evaluates against is possibly a value not directly in your control, such as a user input value, then validating the data and explicitly breaking out of the loop is usually necessary, so you'd want to do it with either method.
The while True format is more pythonic since you know that break is breaking the loop at that exact point, whereas do_next = False could do more stuff before the next evaluation of do_next.
In some languages True is just and alias for the number. You can learn more why this is by reading more about boolean logic.
while True mean infinite loop, this usually use by long process.
you can change
while True:
with
while 1:
To answer your question directly: while the loop condition is True. Which it always is, in this particular bit of code.
while loops continue to loop until the condition is false. For instance (pseudocode):
i = 0
while i < 10
i++
With each iteration of the loop, i will be incremented by 1, until it is 10. At that point, the condition i < 10 is no longer true, and the loop will complete.
Since the condition in while True is explicitly and always true, the loop will never end (until it is broken out of some other way, usually by a construct like break within the loop body).
Nothing evaluates to True faster than True. So, it is good if you use while True instead of while 1==1 etc.
while True:
...
means infinite loop.
The while statement is often used of a finite loop. But using the constant 'True' guarantees the repetition of the while statement without the need to control the loop (setting a boolean value inside the iteration for example), unless you want to break it.
In fact
True == (1 == 1)
While True means loop will run infinitely is no condition is mentioned inside the while loop that breaks it.
You can break the code using 'break' or 'return'
>>> a = ['foo', 'bar', 'baz']
>>> while True:
... if not a:
... break
... print(a.pop(-1))
...
baz
bar
foo
Code copied from the realpython.com
How to use while True in Python?
# Python program to demonstrate
# while loop with True
while True:
pass
If we run the above code then this loop will run infinite number of times. To come out of this loop we will use the break statement  explicitly.
With Break Statement
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))
With Return Statement
Since True always evaluates to True , the loop will run indefinitely, until something within the loop return.
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
k = 1
while True:
total_time = 0
for i in piles:
total_time += ceil(i / k)
if total_time > h:
k += 1
else:
return k
Anything can be taken as True until the opposite is presented. This is the way duality works. It is a way that opposites are compared. Black can be True until white at which point it is False. Black can also be False until white at which point it is True. It is not a state but a comparison of opposite states. If either is True the other is wrong. True does not mean it is correct or is accepted. It is a state where the opposite is always False. It is duality.

Python - How to find which condition is true in if statement?

I have an if statement has many conditions, for example:
if(0 > 1 or 9 < 10 or 2 == 1):
print('Hello World!')
so i wanna know which is the right condition that let the if statement continues to print hello world? "without using another if statement or elif"
In my code I have lots of conditions so it's difficult to use a lot of else statements to just know what is the right condition was.
In general, it's impossible - each condition is evaluated, we can only get a result.
However, if instead of ors, we have them stored* in a list like this:
conditions = [0>1, 9<10, 2==1] # it gets evaluated here!*
if any(conditions):
print('Hello World!')
we could get the index of the True element by doing conditions.index(True).
[*] But be aware that conditions doesn't consist of pure conditions but of Trues and Falses because they got evaluated. That's why I said it's impossible to get the condition itself.
I don't know why you would ever want to use this but okay...
You need to return a value which has a special __bool__ so I would define a class.
The class will have one instance variable, index to indecate the first True condition, or None if there's no True condition.
The __bool__ function then only needs to check whether index is None:
class Any:
def __init__(self, *conditions):
self.index = None
for i, cond in enumerate(conditions):
if cond:
self.index = i
break
def __bool__(self):
return self.index is not None
Example usage:
if o := Any(0 > 1, 9 < 10, 2 == 1):
print(f'The index of the first True condition is {o.index}')
For hard coded conditions like in your example, a good IDE should have an indicator and propose that you simplify the condition.
If you have variables in the condition, this will of course not be possible. In such a case, I would refactor the code and introduce additional semantics by using a variable name for the individual boolean parts of the condition.
In PyCharm, the shortcut Ctrl+Alt+V extracts a condition into a variable.
A more realistic example (before):
class Customer:
def __init__(self, age, totalsales, paymenttype):
self.age = age
self.totalsales = totalsales
self.paymenttype = paymenttype
c = Customer(21, 3000, 2)
if c.age > 18 or c.totalsales > 5000 or c.paymenttype == 1:
print('Hello World!')
After:
c = Customer(21, 3000, 2)
is_adult = c.age > 18
is_vip = c.totalsales > 5000
is_payed_in_advance = c.paymenttype == 1
if is_adult or is_vip or is_payed_in_advance:
print('Hello World!')
When you reach the if-statement, you can inspect each part of the condition in the debugger.
Note that this may change the behavior of your program, because with the changed code, each condition is evaluated, whereas short circuiting may have been applied before. However, I never ran into a situation where this caused a problem.
Chained boolean expressions will be evaluated from left to right. If one of the chained statements is evaluated as being True, the remaining conditions will not be checked.
Assuming second_condition is fulfilled and hence will be evaluated as True, the following pseudo-code snipped would evaluate first_condition as False and then enter the if statement because of second_condition being True. However, third_condition will not be checked as another check before was already evaluated as True and thus the complete statement will become True:
if (first_condition or second_condition or third_condition):
pass
Knowing which condition was evaluated as True is not possible with the approach shown above. Therefore, I would suggest rewriting your checks as follows:
def handle_true(condition):
pass
if first_condition:
handle_true('first')
elif second_condition:
handle_true('second')
elif third_condition:
handle_true('third')
else:
pass
The if/elif will be evaluated in the same way as your chained or expression. If one condition fails, the next will be checked. If one of the given conditions is evaluated as True the branch will be entered. If none of the given conditions is fulfilled, the default else will be entered.
Combining this with the small helper function handle_true() should do the trick and not only provide a way to check which condition fired, but also provide a single place for handling any True condition.
I think that a good option will be to create a list of condition and to check you the item of your list in a loop.
cond=[True, False, True, 5>10,True,False,1==1,3<-1,'a' == 'a'] # assume this is your list
for i in range(len(cond)):
if cond[i]:
print(i) # will return the Item adress correspending to True
You can do:
print(0 > 1) print(9 < 10)
It will print true or false

Alternate syntax for "while True" loop?

I'm still relatively new to Python and have been using statements like the following:
flag = False
while flag == False:
# Do something here that might set the flag to True,
flag = True
However this could be written like so:
while not flag:
# Do something...
flag = True
while flag is False:
# Do something...
flag = True
With a further (preferred?) way of writing this type of loop:
while True:
# Do something and if wanting wanting to break out of loop,
break
The first three methods are more explicit, so why are they (or one of them) not preferred over the fourth method? Are there any differences between the first three ways of writing the "while flag == False"?
All of them are technically different.
Example 1
Say you have a function call that doesn't return anything meaningful, as follows:
def fun(x=None):
return x
Now, for your while loops, all of which will be defined as follows:
def while1():
flag = False
while flag == False:
flag = fun(None)
def while2():
flag = False
while flag is False:
flag = fun(None)
def while3():
flag = False
while not flag:
flag = fun(None)
In this case, only while1 and while2 will terminate. Since bool(None) evaluates to False, while3 will continue infinitely, but since None != False and None is not False, both while1 and while2 will terminate.
Now, this gets more interesting with more complicated examples.
Example 2
def fun(x):
return x
Now, for each of our loops, we're going to change flag = fun() to flag = fun(0).
In this case, while1 and while3 terminate, while while2 continues indefinitely. This is because bool(0) == False, and 0 == False, but 0 is not False.
Example 3 -- Mutables
Now, this gets a lot more complicated with mutables, which is why the explicit versus implicit depends situation to situation. Mutables are any object that can be modified, and include dicts, lists. Immutable objects are anything that cannot be modified, such as tuples, ints, floats, strs.
Say I have the following:
a = []
b = []
In this case, bool(a) == False, and a == b, but a is not b. In short, there is no, simple, steadfast rule for how to check falsey or truthey values.
However, there are general rules.
General Rules
Checking None vs. Other
If you accept any value other than None, check x is None.
Checking mutables
Never use x is b, since mutables can have different IDs, unless if you explicitly want to check to an object with the same ID (id(x) == id(b).
Typically, check not x or x == b
>>> a = []
>>> b = []
>>> a is b
False
>>> a == b
True
>>> not a
True
Checking strs, floats and ints
For strs, floats and ints, always check x == b and not x is b. This is since for short strs, floats, ints, the results can be true if x == b, but for more complicated cases, your code will stop working.
For example:
>>> a = 1
>>> a is 1
True
>>> a = 10000000
>>> a is 10000000
False
Checking booleans
For booleans, you can do any of the above, but not x is preferable to x == b or x is b.
Finally... While Loops
If you can, always convert a while loop to a for loop. This isn't always possible, but say you want to do a simple case:
x = 0
while x < 10:
print(x)
x -= 1
This can be converted to:
for x in range(10):
print(x)
The reason for using for loops rather than while loops is if some error occurs in your code, while loops can lead to an indefinite loop and crash your program, while a for loop will always exit.
I don't think there is a preference really. A while-loop will continue to execute the code block as long as the boolean expression specified remains True.
flag == True, not Flag, i < 6 or evaluate to boolean expressions. If you just say while True like in your example, you will just enter an infinite loop. Does that answer your question?
While the first three are more explicit, the last one is more readable and clear. This I would say makes it the greater option above the other three. There won't be any searching for the initialization of some variable for the loop. With that said, all of the methods are perfectly acceptable and you should use the one that is more comfortable for you.
I think the while True: syntax is fine for simple logic. Once you start breaking out of the loop from multiple locations or need to track if the loop was successful then it gets to be messy.
Also, if the while condition is named correctly then it sort of documents why you are looping.
while not end_of_file:
..read read read..
Avoiding the break statement in loop, IMHO, makes code more readable. Just like avoid multiple return statements in a function.

Why not True == True:

The last point of the style guide http://www.python.org/dev/peps/pep-0008
reads ...
Don't compare boolean values to True or False using ==.
Why?
Edit
Just to make it clear what im asking (and it's indicative of the problem itself), when you write
if something:
print "something is true"
You are doing an implicit conversion to a boolean which may or may not work depending on what true means. IMHO this form of programming is discouraged because of the side effects it can cause.
numberOfApples = -1
if numberOfApples:
print "you have apples" # is not what is intended.
if numberOfApples == True:
print "you have apples" # is also not what is intended.
iHaveApples = numberOfApples > 0
if iHaveApples is True: # Edit: corrected this.. the "is" is better than the ==
print "you have apples" # is correct.
Implicit conversions disguise logical errors. So why does the style guide encourage this?
It means that you should write
if greeting:
Instead of:
if greeting == True:
Similarly, you shouldn't write this either:
if (greeting == True) == True:
The extra tests are redundant and don't add any value to the code, so they should be removed.
IMHO the point of a style guide is to standardise some common constructs, in a way that makes sense, so you won't end up with wildly disparating statements that ultimately do the same thing. More, the unusual forms might suggest that the programmer had some reason to do things a different way, maybe he was trying to achieve something different than what the statement looks like.
If you want to test the truehood/falsehood of a statement, just use the statement itself or precede it by not. If you must ensure the statement evaluates to True or False (not just a truthy/falsy value), you could use statement is True - though the style guide discourages it - or maybe check its type (using isinstance). But that's usually bad design, you should avoid that unless you have a pretty good reason to do so.
Using statement == True is dangerous for many reasons: 1) only work with True, failing with other "truthy" values (like [1]); 2) might produce unexpected results if the value returned by statement redefines __eq__; 3) might produce different results if the order of the arguments is changed, etc. Note that just using the statement may also return a different value for truehood/falsehood if the value implements __nonzero__ or __len__, but for regular usage that's usually not a problem.
Some examples showing how messed up things can be if you deviate from the style:
if True: print True # True
if 1: print True # True
if [1]: print True # True
True is True # True
1 is True # False
[1] is True # False
True == True # True
1 == True # True
[1] == True # False
Edit: some more:
if 1: print True # True
if 2: print True # True
1 == True # True
2 == True # False
1 is True # False
2 is True # False
Update: as #Marcin pointed out, you can use bool to coerce a value to True/False, guaranteeing that only those values will be present. The result of that function is consistent to the default truehood/falsehood of the value (so __nonzero__ and __len__ is taken into account). Some examples:
if bool(1): print True # True
bool(1) == True # True
bool(1) is True # True
if bool(2): print True # True
bool(2) == True # True
bool(2) is True # True
1 or 2 # 1
1 and 2 # 2
bool(1) or bool(2) # True
bool(1) and bool(2) # True
bool(1) == bool(2) # True
bool(1) is bool(2) # True
Because it's redundant.
if hasChildren:
is the same as
if hasChildren == True:
but is briefer and easier to read.
In sort:
# A, Good:
if numberOfApples > 0:
print "you have apples"
# B, Also good:
iHaveApples = numberOfApples > 0
if iHaveApples:
print "you have apples"
# C, Bad:
iHaveApples = numberOfApples > 0
if iHaveApples == True:
print "you have apples"
Why would you ever pick C over A or B?
Update:
I think you're sweating bullets over some corner cases, but if those corner cases matter in your project use the appropriate comparison. In general we do know something about the type of iHaveApples, for example we know that it's the result of a comparison using >. It's reasonable, and good practice I believe, to use that information in your code. If you're asking, "what if I think it's a bool and it turns out to be an int or something else." Than I would say you have a bug in your code, you should find it, fix it, and write a test in case you make the same mistake again. Don't rely on python to find your mistakes at runtime.
I'll assert, and leave up to you to prove if you want, that if iHaveApples: behaves exactly the same, but runs faster, as if iHaveApples is True: when you know for sure that iHaveApples is a bool. Lastly I'll give an example of when is would result in undesired behavior, at least in my opinion.
>>> import numpy
>>> totalApples = numpy.sum([1, 2, 3]) == 6
>>> totalApples
True
>>> totalApples is True
False
I'll let you figure out why that doesn't work if you want (hint, check type(totalApples)).

What does "while True" mean in Python?

def play_game(word_list):
hand = deal_hand(HAND_SIZE) # random init
while True:
cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
if cmd == 'n':
hand = deal_hand(HAND_SIZE)
play_hand(hand.copy(), word_list)
print
elif cmd == 'r':
play_hand(hand.copy(), word_list)
print
elif cmd == 'e':
break
else:
print "Invalid command."
While WHAT is True?
I reckon saying 'while true' is shorthand, but for what? While the variable 'hand' is being assigned a value? And what if the variable 'hand' is not being assigned a value?
while True means loop forever. The while statement takes an expression and executes the loop body while the expression evaluates to (boolean) "true". True always evaluates to boolean "true" and thus executes the loop body indefinitely. It's an idiom that you'll just get used to eventually! Most languages you're likely to encounter have equivalent idioms.
Note that most languages usually have some mechanism for breaking out of the loop early. In the case of Python it's the break statement in the cmd == 'e' case of the sample in your question.
my question: while WHAT is True?
While True is True.
The while loop will run as long as the conditional expression evaluates to True.
Since True always evaluates to True, the loop will run indefinitely, until something within the loop returns or breaks.
while True is true -- ie always. This is an infinite loop
Note the important distinction here between True which is a keyword in the language denoting a constant value of a particular type, and 'true' which is a mathematical concept.
my question: while WHAT is 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.
In this context, I suppose it could be interpreted as
do
...
while cmd != 'e'
True is always True, so while True will loop forever.
The while keyword takes an expression, and loops while the expression is true. True is an expression that is always true.
As a possibly clarifying example, consider the following:
a = 1
result = a == 1
Here, a == 1 will return True, and hence put True into result. Hence,
a = 1
while a == 1:
...
is equivalent to:
while True:
...
provided you don't alter the value of a inside the while loop.
Formally, True is a Python built-in constant of bool type.
You can use Boolean operations on bool types (at the interactive python prompt for example) and convert numbers into bool types:
>>> print not True
False
>>> print not False
True
>>> print True or False
True
>>> print True and False
False
>>> a=bool(9)
>>> print a
True
>>> b=bool(0)
>>> print b
False
>>> b=bool(0.000000000000000000000000000000000001)
>>> print b
True
And there are "gotcha's" potentially with what you see and what the Python compiler sees:
>>> n=0
>>> print bool(n)
False
>>> n='0'
>>> print bool(n)
True
>>> n=0.0
>>> print bool(n)
False
>>> n="0.0"
>>> print bool(n)
True
As a hint of how Python stores bool types internally, you can cast bool types to integers and True will come out to be 1 and False 0:
>>> print True+0
1
>>> print True+1
2
>>> print False+0
0
>>> print False+1
1
In fact, Python bool type is a subclass of Python's int type:
>>> type(True)
<type 'bool'>
>>> isinstance(True, int)
True
The more important part of your question is "What is while True?" is 'what is True', and an important corollary: What is false?
First, for every language you are learning, learn what the language considers 'truthy' and 'falsey'. Python considers Truth slightly differently than Perl Truth for example. Other languages have slightly different concepts of true / false. Know what your language considers to be True and False for different operations and flow control to avoid many headaches later!
There are many algorithms where you want to process something until you find what you are looking for. Hence the infinite loop or indefinite loop. Each language tend to have its own idiom for these constructs. Here are common C infinite loops, which also work for Perl:
for(;;) { /* loop until break */ }
/* or */
while (1) {
return if (function(arg) > 3);
}
The while True: form is common in Python for indefinite loops with some way of breaking out of the loop. Learn Python flow control to understand how you break out of while True loops. Unlike most languages, for example, Python can have an else clause on a loop. There is an example in the last link.
A while loop takes a conditional argument (meaning something that is generally either true or false, or can be interpreted as such), and only executes while the condition yields True.
As for while True? Well, the simplest true conditional is True itself! So this is an infinite loop, usually good in a game that requires lots of looping. (More common from my perspective, though, is to set some sort of "done" variable to false and then making that true to end the game, and the loop would look more like while not done: or whatever.)
While most of these answers are correct to varying degrees, none of them are as succinct as I would like.
Put simply, using while True: is just a way of running a loop that will continue to run until you explicitly break out of it using break or return. Since True will always evaluate to True, you have to force the loop to end when you want it to.
while True:
# do stuff
if some_condition:
break
# do more stuff - code here WILL NOT execute when `if some_condition:` evaluates to True
While normally a loop would be set to run until the while condition is false, or it reaches a predefined end point:
do_next = True
while do_next:
# do stuff
if some_condition:
do_next = False
# do more stuff - code here WILL execute even when `if some_condition:` evaluates to True
Those two code chunks effectively do the same thing
If the condition your loop evaluates against is possibly a value not directly in your control, such as a user input value, then validating the data and explicitly breaking out of the loop is usually necessary, so you'd want to do it with either method.
The while True format is more pythonic since you know that break is breaking the loop at that exact point, whereas do_next = False could do more stuff before the next evaluation of do_next.
In some languages True is just and alias for the number. You can learn more why this is by reading more about boolean logic.
while True mean infinite loop, this usually use by long process.
you can change
while True:
with
while 1:
To answer your question directly: while the loop condition is True. Which it always is, in this particular bit of code.
while loops continue to loop until the condition is false. For instance (pseudocode):
i = 0
while i < 10
i++
With each iteration of the loop, i will be incremented by 1, until it is 10. At that point, the condition i < 10 is no longer true, and the loop will complete.
Since the condition in while True is explicitly and always true, the loop will never end (until it is broken out of some other way, usually by a construct like break within the loop body).
Nothing evaluates to True faster than True. So, it is good if you use while True instead of while 1==1 etc.
while True:
...
means infinite loop.
The while statement is often used of a finite loop. But using the constant 'True' guarantees the repetition of the while statement without the need to control the loop (setting a boolean value inside the iteration for example), unless you want to break it.
In fact
True == (1 == 1)
While True means loop will run infinitely is no condition is mentioned inside the while loop that breaks it.
You can break the code using 'break' or 'return'
>>> a = ['foo', 'bar', 'baz']
>>> while True:
... if not a:
... break
... print(a.pop(-1))
...
baz
bar
foo
Code copied from the realpython.com
How to use while True in Python?
# Python program to demonstrate
# while loop with True
while True:
pass
If we run the above code then this loop will run infinite number of times. To come out of this loop we will use the break statement  explicitly.
With Break Statement
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))
With Return Statement
Since True always evaluates to True , the loop will run indefinitely, until something within the loop return.
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
k = 1
while True:
total_time = 0
for i in piles:
total_time += ceil(i / k)
if total_time > h:
k += 1
else:
return k
Anything can be taken as True until the opposite is presented. This is the way duality works. It is a way that opposites are compared. Black can be True until white at which point it is False. Black can also be False until white at which point it is True. It is not a state but a comparison of opposite states. If either is True the other is wrong. True does not mean it is correct or is accepted. It is a state where the opposite is always False. It is duality.

Categories