Related
Apologies if this has been asked before, but I have searched in vain for an answer to my exact question. Basically, with Python 2.7, I have a program running a series of geoprocessing tools, depended on what is reqested via a series of True/False variables that the user adjusts in the script e.g.
x = True
if x:
run function
However, I have now discovered that x does not need to be literally "True" for the function to run. For example:
In: x = True
if x:
print True
Out: True
In: x = 123
if x:
print True
Out: True
In: x = 'False'
if x:
print True
Out: True
In: x = False
if x:
print True
Out:
So any value other than False appears to evaluate to True, which would not be the case for if x == True or if x is True. Seeing as PEP 8 strongly recommends only using the if x: variant, can anybody explain why this behaviour occurs? It seems that if x: is more a test for "if x is not False" or "if x exists". With that in mind, I believe I should be using if x is True: in this case, despite what PEP 8 has to say.
The following values in Python are false in the context of if and other logical contexts:
False
None
numeric values equal to 0, such as 0, 0.0, -0.0
empty strings: '' and u''
empty containers (such as lists, tuples and dictionaries)
anything that implements __bool__ (in Python3) to return False, or __nonzero__ (in Python2) to return False or 0.
anything that doesn't implement __bool__ (in Python3) or __nonzero__ (in Python2), but does implement __len__ to return a value equal to 0
An object is considered "false" if any of those applies, and "true" otherwise, regardless of whether it's actually equal to or identical with False or True
Now, if you've arranged that x is necessarily one of the objects True or False, then you can safely write if x. If you've arranged that the "trueness" of x indicates whether or not to perform the operation, regardless of type, then you can safely write if x. Where you can write that you should prefer to do so, since it's cleaner to read.
Normally, if it is allowed for x to take the value True then you're in one of those two cases, and so you would not write if x is True. The important thing is to correctly document the meaning of x, so that it reflects the test used in the code.
Python programmers are expected to know what's considered true, so if you just document, "runs the function if x is true", then that expresses what your original code does. Documenting it, "runs the function if x is True" would have a different meaning, and is less commonly used precisely because of the style rule in PEP8 that says to test for trueness rather than the specific value True.
However, if you wanted the code to behave differently in the case where x is an empty container from the case where it is None, then you would write something like if x is not None.
I'd like to add a short example where those 3 tests differ:
def test(x):
print(x, ":", bool(x), x == True, x is True)
test("something")
test(1)
test(True)
The output (pretty formatted):
# "something" : True False False
# 1 : True True False
# True : True True True
x = 'False'
x = 123
Are both True
Other truth values.
The document explains other values.
As far as the PEP8 reason, its far more semantic to read if this_file_is_green
Other falsey values include 0, '', []. You should just use the if x: version.
It goes without saying that you should write code that does what you need. But in most cases, you simply don't need to say == True or is True, because you don't need to distinguish True from other "truthy" values. So it's recommended to leave that out for simplicity.
The case where you definitely should use == True or is True is when you do need to distinguish True from other truthy values.
In your example, do you care about the difference between True and 123? That would tell you which way to code it.
One thing about coding == True or is True: it will raise a minor red flag when other developers read your code. They won't think it's wrong, they will just wonder why it's there and will want to know why it's important to treat True differently from other truthy values in this particular case.
In other words, if you don't need it, it's best not to use it.
The ability to say
if x:
...
is considered a feature. You can also specify when the test should be considered to pass or not for user defined classes (just define the method __nonzero__ in Python 2.x or __bool__ in Python 3).
For example for strings and containers like lists, dictionaries or sets the test if x ... means "if x is not empty".
Note that the rationale is not that this allows less code to write, but that resulting code is easier to read and to understand.
If you like instead to write if x is True ... have you considered to go farther down that path to if (x is True) is True ... or if ((x is True) is True) is True ... ? :-)
In Python 2.7, if a: and if a==True are not giving the same output for values different to 1. Here are some snippets of code to demonstrate the different behaviors:
with a=1
a=1
if a==True:
print (a,"True")
else:
print (a,"Not True")
output> (1,True)
a=1
if a:
print (a,"True")
else:
print (a,"Not True")
output> (1, True)
with a=2
a=2
if a:
print (a,"True")
else:
print (a,"Not True")
output> (2, True)
a=2
if a==True:
print (a,"True")
else:
print (a,"Not True")
output> (2, Not True)
if you use if x ,it means it has to evaluate x for its truth value.But when you use x ==True or x is True.It means checking whether type(x)==bool and whether x is True.
attention : x is True is no equal to bool(x)==True
when you use x is True , you are checking the id of x and True.
Apologies if this has been asked before, but I have searched in vain for an answer to my exact question. Basically, with Python 2.7, I have a program running a series of geoprocessing tools, depended on what is reqested via a series of True/False variables that the user adjusts in the script e.g.
x = True
if x:
run function
However, I have now discovered that x does not need to be literally "True" for the function to run. For example:
In: x = True
if x:
print True
Out: True
In: x = 123
if x:
print True
Out: True
In: x = 'False'
if x:
print True
Out: True
In: x = False
if x:
print True
Out:
So any value other than False appears to evaluate to True, which would not be the case for if x == True or if x is True. Seeing as PEP 8 strongly recommends only using the if x: variant, can anybody explain why this behaviour occurs? It seems that if x: is more a test for "if x is not False" or "if x exists". With that in mind, I believe I should be using if x is True: in this case, despite what PEP 8 has to say.
The following values in Python are false in the context of if and other logical contexts:
False
None
numeric values equal to 0, such as 0, 0.0, -0.0
empty strings: '' and u''
empty containers (such as lists, tuples and dictionaries)
anything that implements __bool__ (in Python3) to return False, or __nonzero__ (in Python2) to return False or 0.
anything that doesn't implement __bool__ (in Python3) or __nonzero__ (in Python2), but does implement __len__ to return a value equal to 0
An object is considered "false" if any of those applies, and "true" otherwise, regardless of whether it's actually equal to or identical with False or True
Now, if you've arranged that x is necessarily one of the objects True or False, then you can safely write if x. If you've arranged that the "trueness" of x indicates whether or not to perform the operation, regardless of type, then you can safely write if x. Where you can write that you should prefer to do so, since it's cleaner to read.
Normally, if it is allowed for x to take the value True then you're in one of those two cases, and so you would not write if x is True. The important thing is to correctly document the meaning of x, so that it reflects the test used in the code.
Python programmers are expected to know what's considered true, so if you just document, "runs the function if x is true", then that expresses what your original code does. Documenting it, "runs the function if x is True" would have a different meaning, and is less commonly used precisely because of the style rule in PEP8 that says to test for trueness rather than the specific value True.
However, if you wanted the code to behave differently in the case where x is an empty container from the case where it is None, then you would write something like if x is not None.
I'd like to add a short example where those 3 tests differ:
def test(x):
print(x, ":", bool(x), x == True, x is True)
test("something")
test(1)
test(True)
The output (pretty formatted):
# "something" : True False False
# 1 : True True False
# True : True True True
x = 'False'
x = 123
Are both True
Other truth values.
The document explains other values.
As far as the PEP8 reason, its far more semantic to read if this_file_is_green
Other falsey values include 0, '', []. You should just use the if x: version.
It goes without saying that you should write code that does what you need. But in most cases, you simply don't need to say == True or is True, because you don't need to distinguish True from other "truthy" values. So it's recommended to leave that out for simplicity.
The case where you definitely should use == True or is True is when you do need to distinguish True from other truthy values.
In your example, do you care about the difference between True and 123? That would tell you which way to code it.
One thing about coding == True or is True: it will raise a minor red flag when other developers read your code. They won't think it's wrong, they will just wonder why it's there and will want to know why it's important to treat True differently from other truthy values in this particular case.
In other words, if you don't need it, it's best not to use it.
The ability to say
if x:
...
is considered a feature. You can also specify when the test should be considered to pass or not for user defined classes (just define the method __nonzero__ in Python 2.x or __bool__ in Python 3).
For example for strings and containers like lists, dictionaries or sets the test if x ... means "if x is not empty".
Note that the rationale is not that this allows less code to write, but that resulting code is easier to read and to understand.
If you like instead to write if x is True ... have you considered to go farther down that path to if (x is True) is True ... or if ((x is True) is True) is True ... ? :-)
In Python 2.7, if a: and if a==True are not giving the same output for values different to 1. Here are some snippets of code to demonstrate the different behaviors:
with a=1
a=1
if a==True:
print (a,"True")
else:
print (a,"Not True")
output> (1,True)
a=1
if a:
print (a,"True")
else:
print (a,"Not True")
output> (1, True)
with a=2
a=2
if a:
print (a,"True")
else:
print (a,"Not True")
output> (2, True)
a=2
if a==True:
print (a,"True")
else:
print (a,"Not True")
output> (2, Not True)
if you use if x ,it means it has to evaluate x for its truth value.But when you use x ==True or x is True.It means checking whether type(x)==bool and whether x is True.
attention : x is True is no equal to bool(x)==True
when you use x is True , you are checking the id of x and True.
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.
Apologies if this has been asked before, but I have searched in vain for an answer to my exact question. Basically, with Python 2.7, I have a program running a series of geoprocessing tools, depended on what is reqested via a series of True/False variables that the user adjusts in the script e.g.
x = True
if x:
run function
However, I have now discovered that x does not need to be literally "True" for the function to run. For example:
In: x = True
if x:
print True
Out: True
In: x = 123
if x:
print True
Out: True
In: x = 'False'
if x:
print True
Out: True
In: x = False
if x:
print True
Out:
So any value other than False appears to evaluate to True, which would not be the case for if x == True or if x is True. Seeing as PEP 8 strongly recommends only using the if x: variant, can anybody explain why this behaviour occurs? It seems that if x: is more a test for "if x is not False" or "if x exists". With that in mind, I believe I should be using if x is True: in this case, despite what PEP 8 has to say.
The following values in Python are false in the context of if and other logical contexts:
False
None
numeric values equal to 0, such as 0, 0.0, -0.0
empty strings: '' and u''
empty containers (such as lists, tuples and dictionaries)
anything that implements __bool__ (in Python3) to return False, or __nonzero__ (in Python2) to return False or 0.
anything that doesn't implement __bool__ (in Python3) or __nonzero__ (in Python2), but does implement __len__ to return a value equal to 0
An object is considered "false" if any of those applies, and "true" otherwise, regardless of whether it's actually equal to or identical with False or True
Now, if you've arranged that x is necessarily one of the objects True or False, then you can safely write if x. If you've arranged that the "trueness" of x indicates whether or not to perform the operation, regardless of type, then you can safely write if x. Where you can write that you should prefer to do so, since it's cleaner to read.
Normally, if it is allowed for x to take the value True then you're in one of those two cases, and so you would not write if x is True. The important thing is to correctly document the meaning of x, so that it reflects the test used in the code.
Python programmers are expected to know what's considered true, so if you just document, "runs the function if x is true", then that expresses what your original code does. Documenting it, "runs the function if x is True" would have a different meaning, and is less commonly used precisely because of the style rule in PEP8 that says to test for trueness rather than the specific value True.
However, if you wanted the code to behave differently in the case where x is an empty container from the case where it is None, then you would write something like if x is not None.
I'd like to add a short example where those 3 tests differ:
def test(x):
print(x, ":", bool(x), x == True, x is True)
test("something")
test(1)
test(True)
The output (pretty formatted):
# "something" : True False False
# 1 : True True False
# True : True True True
x = 'False'
x = 123
Are both True
Other truth values.
The document explains other values.
As far as the PEP8 reason, its far more semantic to read if this_file_is_green
Other falsey values include 0, '', []. You should just use the if x: version.
It goes without saying that you should write code that does what you need. But in most cases, you simply don't need to say == True or is True, because you don't need to distinguish True from other "truthy" values. So it's recommended to leave that out for simplicity.
The case where you definitely should use == True or is True is when you do need to distinguish True from other truthy values.
In your example, do you care about the difference between True and 123? That would tell you which way to code it.
One thing about coding == True or is True: it will raise a minor red flag when other developers read your code. They won't think it's wrong, they will just wonder why it's there and will want to know why it's important to treat True differently from other truthy values in this particular case.
In other words, if you don't need it, it's best not to use it.
The ability to say
if x:
...
is considered a feature. You can also specify when the test should be considered to pass or not for user defined classes (just define the method __nonzero__ in Python 2.x or __bool__ in Python 3).
For example for strings and containers like lists, dictionaries or sets the test if x ... means "if x is not empty".
Note that the rationale is not that this allows less code to write, but that resulting code is easier to read and to understand.
If you like instead to write if x is True ... have you considered to go farther down that path to if (x is True) is True ... or if ((x is True) is True) is True ... ? :-)
In Python 2.7, if a: and if a==True are not giving the same output for values different to 1. Here are some snippets of code to demonstrate the different behaviors:
with a=1
a=1
if a==True:
print (a,"True")
else:
print (a,"Not True")
output> (1,True)
a=1
if a:
print (a,"True")
else:
print (a,"Not True")
output> (1, True)
with a=2
a=2
if a:
print (a,"True")
else:
print (a,"Not True")
output> (2, True)
a=2
if a==True:
print (a,"True")
else:
print (a,"Not True")
output> (2, Not True)
if you use if x ,it means it has to evaluate x for its truth value.But when you use x ==True or x is True.It means checking whether type(x)==bool and whether x is True.
attention : x is True is no equal to bool(x)==True
when you use x is True , you are checking the id of x and True.
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.