Why does PyCharm highlight the boolean variable nearby the return with Local variable "boolean" might be referenced before assignment?
This code checks whether a number is prime or not:
import random
import math
import time
def prime_t(x):
print x
if x < 2:
return False
if x == 2:
return True
if x == 3:
return True
for i in range(2, int(math.sqrt(x))+1):
if x % i == 0:
boolean = False
break
else:
boolean = True
return boolean
random.seed()
how_much = input()
start = time.time()
for i in range(0, how_much):
print(prime_t(random.randint(0, 1000)))
print time.time()-start
I've read that might be some problem with global variables, but there's no ones which might be used in prime_t(). I had similar thing - exception while executing the code, but I think it has been eliminated with if x == 2 and if x == 3.
What else might be the problem?
PyCharm is not certain that boolean will be set. It is not smart enough to work out the flow of your code, so it doesn't know that your for loop will always have at least 1 iteration (since x > 3 is true by that point, provided x is an integer, of course).
Instead, it assumes that variables bound in a for loop could potentially never be set, and thus raises this warning.
The work-around is of course to set boolean = False before the loop, just to shut it up. It is only a warning, you could also just ignore it as the IDE is trying to help you but misunderstood.
Alternatively, instead of using a flag variable, you can use return False inside the for loop where you now use break, and return True at the end of your function:
def prime_t(x):
if x < 2:
return False
if x in {2, 3}:
return True
for i in range(2, int(math.sqrt(x))+1):
if x % i == 0:
return False
return True
For those looking to ignore this, put
# noinspection PyUnboundLocalVariable
Above the line.
Thanks to: https://github.com/whitews/pc-inspection-suppression-list/blob/master/suppress-inspection.csv
In general, code that's inside a for or while loop doesn't have to run. The condition for a while loop could be unmet as soon as the loop is reached initially. The for loop could be trying to iterate over something that's empty. If the loop doesn't run, and the code in the loop is the only place that a particular variable gets set, then it wouldn't get set. Trying to use it would cause an UnboundLocalError (a subtype of NameError) to be raised.
IDEs often try to detect this situation and offer warnings. Because they are warnings, they will be conservative. Python is a highly dynamic language and there's often very little that you can prove about the code's behaviour before it runs. So pretty well any loop that doesn't use constant, literal data (for x in [1, 2, 3]:) needs to be treated as "might not run at all".
And, indeed, if I try out the example function at the interpreter prompt, I can easily get that UnboundLocalError:
>>> prime_t(math.pi)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 14, in prime_t
UnboundLocalError: local variable 'boolean' referenced before assignment
After all, nothing else in the code type-checked the value; and pi isn't equal to 3, nor to 2, nor is it less than 2.
There are several reasonable approaches to the problem, in context.
We can simply assign boolean = True before the loop:
boolean = True
for i in range(2, int(math.sqrt(x))+1):
if x % i == 0:
boolean = False
break
return boolean
We can use an else clause on the loop to set the "default" value:
for i in range(2, int(math.sqrt(x))+1):
if x % i == 0:
boolean = False
break
else:
boolean = True
return boolean
The else block code runs whenever there isn't a break out of the loop; in particular, it runs if the loop doesn't run (since there was nothing to break out of). So static checking tools should be able to verify that our bases are covered. Many people don't like this syntax because it's confusing and often unintended (it looks like a typo, right?). However, this use pattern is pretty much exactly why it's in the language. (That said, I think we can do better; keep reading.)
Since there is nothing more to do after this loop in the function, we don't need a flag at all; we can return False as soon as we find a factor, and return True at the end of the function (since we didn't find one if we got this far):
for i in range(2, int(math.sqrt(x))+1):
if x % i == 0:
return False
return True
(Notice that in all of these cases, I removed the else from the if - because it doesn't serve a purpose here. It doesn't make a lot of logical sense to keep reminding ourselves that we didn't find a factor yet - we wouldn't still be looping if we did.)
All of that said, for "searching" loops like these I prefer to avoid explicit for loops altogether. The built-in any and all functions are practically designed for the purpose - especially when paired with a generator expression, which ensures their short-circuiting behaviour stays relevant:
return not any(x % i == 0 for i in range(2, int(math.sqrt(x))+1))
Equivalently (following de Morgan's law):
return all(x % i != 0 for i in range(2, int(math.sqrt(x))+1))
Related
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.
def p3(x,y,ls2):
for i in ls2:
if abs(i[0]-x)==abs(i[1]-y):
c=0
break
else:
c=1
if c==0:
return False
else:
return True
Even I have assigned c in the same function, it still displays "local variable 'c' referenced before assignment"
As the comment by Suraj S says, the problem is if ls2 is an empty list (iterable). Even if that were not a problem, c is a local variable inside the for loop and even though Python allows accessing it outside its scope, it is not a good practice to do so. So it is correct to default initialize it first before running the loop. You can default it to 0 or 1 depending on your use case.
Also, practice Boolean Zen. Don't make redundant checks with booleans. It is better to use True and False instead of 0 and 1.
def p3(x,y,ls2):
c = True # default
for i in ls2:
if abs(i[0]-x)==abs(i[1]-y):
c = False
break
# no need for else at all
return c
Even better:
def p3(x,y,ls2):
for i in ls2:
if abs(i[0]-x)==abs(i[1]-y):
return False
# no need for else at all
return True
If I understand correctly your function, you could simplify it to the following:
def p3(x, y, ls2):
# if no list or list is empty
if not ls2: # the condition could be more convoluted if needed
return 'invalid input' # or return boolean depending on use case
for i in ls2:
# if condition is matched return immediately
if abs(i[0]-x)==abs(i[1]-y):
return False
# the condition was not matched in loop, return default True
return True
You could even simplify more using all that will stop prematurely if the condition is met:
def p3(x, y, ls2):
# if no list or list is empty
if not ls2: # the condition could be more convoluted if needed
return 'invalid input' # or return boolean depending on use case
return all(abs(i[0]-x)!=abs(i[1]-y) for i in ls2)
# or: return not any(abs(i[0]-x)==abs(i[1]-y) for i in ls2)
In general, if you instantiate a variable (namely c) inside of a for loop, it's best not to use that variable outside of that for loop.
The practical reason for this is that you can't be sure that for loop will run and so the variable might not get instantiated. The more high-level reason is to maintain a sense of scope in your code, or "what happens in the for loop, stays in the for loop", if you will.
So in your case, I would recommend instantiating c with a 'default' value (depending on what your logic is) before the for loop starts, so that even if the for loop runs 0 times, c still has a value.
Alternatively, this entire function could be implemented as
def p3(x, y, ls2):
return not any([abs(i[0]-x)==abs(i[1]-y) for i in ls2])
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.
If I have a function with multiple conditional statements where every branch gets executed returns from the function. Should I use multiple if statements, or if/elif/else? For example, say I have a function:
def example(x):
if x > 0:
return 'positive'
if x < 0:
return 'negative'
return 'zero'
Is it better to write:
def example(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
Both have the same outcome, but is one more efficient or considered more idiomatic than the other?
Edit:
A couple of people have said that in the first example both if statements are always evaluated, which doesn't seem to be the case to me
for example if I run the code:
l = [1,2,3]
def test(a):
if a > 0:
return a
if a > 2:
l.append(4)
test(5)
l will still equal [1,2,3]
I'll expand out my comment to an answer.
In the case that all cases return, these are indeed equivalent. What becomes important in choosing between them is then what is more readable.
Your latter example uses the elif structure to explicitly state that the cases are mutually exclusive, rather than relying on the fact they are implicitly from the returns. This makes that information more obvious, and therefore the code easier to read, and less prone to errors.
Say, for example, someone decides there is another case:
def example(x):
if x > 0:
return 'positive'
if x == -15:
print("special case!")
if x < 0:
return 'negative'
return 'zero'
Suddenly, there is a potential bug if the user intended that case to be mutually exclusive (obviously, this doesn't make much sense given the example, but potentially could in a more realistic case). This ambiguity is removed if elifs are used and the behaviour is made visible to the person adding code at the level they are likely to be looking at when they add it.
If I were to come across your first code example, I would probably assume that the choice to use ifs rather than elifs implied the cases were not mutually exclusive, and so things like changing the value of x might be used to change which ifs execute (obviously in this case the intention is obvious and mutually exclusive, but again, we are talking about less obvious cases - and consistency is good, so even in a simple example when it is obvious, it's best to stick to one way).
Check this out to understand the difference:
>>> a = 2
>>> if a > 1: a = a+1
...
>>> if a > 2: a = a+1
...
>>> a
4
versus
>>> a = 2
>>> if a > 1: a = a+1
... elif a > 2: a = a+1
...
>>> a
3
The first case is equivalent to two distinct if's with empty else statements (or imagine else: pass); in the second case elif is part of the first if statement.
In some cases, elif is required for correct semantics. This is the case when the conditions are not mutually exclusive:
if x == 0: result = 0
elif y == 0: result = None
else: result = x / y
In some cases it is efficient because the interpreter doesn't need to check all conditions, which is the case in your example. If x is negative then why do you check the positive case? An elif in this case also makes code more readable as it clearly shows only a single branch will be executed.
In general (e.g. your example), you would always use an if..elif ladder to explicitly show the conditions are mutually-exclusive. It prevents ambiguity, bugs etc.
The only reason I can think of that you might ever not use elif and use if instead would be if the actions from the body of the preceding if statement (or previous elif statements) might have changed the condition so as to potentially make it no longer mutually exclusive. So it's no longer really a ladder, just separate concatenated if(..elif..else) blocks. (Leave an empty line between the separate blocks, for good style, and to prevent someone accidentally thinking it should have been elif and 'fixing' it)
Here's a contrived example, just to prove the point:
if total_cost>=10:
if give_shopper_a_random_discount():
print 'You have won a discount'
total_cost -= discount
candidate_prime = True
if total_cost<10:
print 'Spend more than $10 to enter our draw for a random discount'
You can see it's possible to hit both conditions, if the first if-block applies the discount, so then we also execute the second, which prints a message which would be confusing since our original total had been >=10.
An elif here would prevent that scenario.
But there could be other scenarios where we want the second block to run, even for that scenario.
if total_cost<10:
<some other action we should always take regardless of original undiscounted total_cost>
In regards to the edit portion of your question when you said:
"A couple of people have said that in the first example both if statements are always evaluated, which doesn't seem to be the case to me"
And then you provided this example:
l = [1,2,3]
def test(a):
if a > 0:
return a
if a > 2:
l.append(4)
test(5)
Yes indeed the list l will still equal [1,2,3] in this case, ONLY because you're RETURNING the result of running the block, because the return statement leads to exiting the function, which would result in the same thing if you used elif with the return statement.
Now try to use the print statement instead of the return one, you'll see that the 2nd if statement will execute just fine, and that 4 will indeed be appended to the list l using append.
Well.. now what if the first ifstatement changes the value of whatever is being evaluated in the 2nd if statement?
And yes that's another situation. For instance, say you have a variable x and you used if statement to evaluate a block of code that actually changed the x value.
Now, if you use another if statement that evaluates the same variable x will be wrong since you're considering x value to be the same as its initial one, while in fact it was changed after the first if was executed. Therefore your code will be wrong.
It happens pretty often, and sometimes you even want it explicitly to be changed. If that's how you want your code to behave, then yes you should use multiple if's which does the job well. Otherwise stick to elif.
In my example, the 1st if block is executed and changed the value of x, which lead to have the 2nd if evaluates a different x (since its value was changed).
That's where elif comes in handy to prevent such thing from happening, which is the primary benefit of using it.
The other secondary good benefit of using elif instead of multiple if's is to avoid confusion and better code readability.
Consider this For someone looking for a easy way:
>>> a = ['fb.com', 'tw.com', 'cat.com']
>>> for i in a:
... if 'fb' in i:
... pass
... if 'tw' in i:
... pass
... else:
... print(i)
output:
fb.com
cat.com
And
>>> a = ['fb.com', 'tw.com', 'cat.com']
>>> for i in a:
... if 'fb' in i:
... pass
... elif 'tw' in i:
... pass
... else:
... print(i)
Output:
cat.com
'If' checks for the first condition then searches for the elif or else, whereas using elif, after if, it goes on checking for all the elif condition and lastly going to else.
elif is a bit more efficient, and it's quite logical: with ifs the program has to evaluate each logical expression every time. In elifs though, it's not always so. However, in your example, this improvement would be very, very small, probably unnoticeable, as evaluating x > 0 is one of the cheapest operations.
When working with elifs it's also a good idea to think about the best order. Consider this example:
if (x-3)**3+(x+1)**2-6*x+4 > 0:
#do something 1
elif x < 0:
#do something 2
Here the program will have to evaluate the ugly expression every time! However, if we change the order:
if x < 0:
#do something 2
elif (x-3)**3+(x+1)**2-6*x+4 > 0:
#do something 1
Now the program will first check if x < 0 (cheap and simple) and only if it isn't, will it evaluate the more complicated expression (btw, this code doesn't make much sense, it's just a random example)
Also, what perreal said.
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.