# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True:
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
Why does the while True loop apply to count in this circumstance? I dont understand why the boolean is gauging the result of count. Wouldn't the correct syntax be:
while count:
Any help clarifying this would be appreciated.
It helps if you follow the code step-by-step in a debugger (a simple ide which allows this is PyScripter).
Just a few remarks:
while True is an endless loop. It can only be left by a break or return statement.
therefore the loop will run until the condition count > 10 is met. The break will terminate the loop and the next command (input ...) is executed.
if count == 5, continue tells python to jump immediately to the beginning of the loop without executing the following statement (therefore the "5" ist not printed).
But: follow the code in a debugger!
count is 0, so while count would never even enter the loop, since 0 is False in a boolean context.
Python doesn't have a construct similar to the repeat ... until (condition) found in some other languages. So if you want a loop to always start, but only end when a condition becomes true, the usual way to do it is to set the condition to just True - which, obviously, is always true - and then explicitly test the condition inside the loop, and break out using break.
To answer your comment, the thing that's true here is simply the value True, which as I say will always be the case.
The syntax for a while loop is "while condition." The block beneath the while loop executes until either condition evaluates to False or a break command is executed. "while True" means the condition always is True and the loop won't stop unless a break is execute. It's a frequent python idiom used since python doesn't have a do while loop.
Related
I am new to Python. I am doing some exercise online.
def user_input_checking_even_number_list(user_input_list):
for input_number in user_input_list:
if input_number%2 == 0:
return True
else:
pass
return False
if I key run the code below
user_input_checking_even_number_list([1,3,5,8,9,11,20,21])
It will return True. But I have one question, is the for loop only check until 8 then the for loop will break? or it actually runs and checks until 21 even though the 8 is an even number that already meets the requirement?
At the time when your program was executing the statement return True in your code, input_number was 8 and for loop had more iterations left. But return statement causes this flow to break and immediately return to the code which called the function - which is outside of the function.
Is while True !=0: valid , if so what does it mean? Because in my program using that or "while True" (by itself) provides the same output. I can't remember why I used it before in my code.
Thanks in advance.
This is used to create infinite loops (or loops that exit via a break or return statement within the loop body). The standard way to do this is:
while True:
...
The other version you showed, while True != 0:, is equivalent, but needlessly convoluted. It works because, when treated as an integer, True has the value 1, so it's equivalent to while 1 != 0: which, in turn, is equivalent to while True:, which is the most direct way to express it.
Yes, while True != 0: is valid and it has the same meaning as while True: which you should use from now on.
This works because int(True) evaluates to 1.
It's simple, true != 0 => 1 != 0 is always 1 (true) .
In the following code snippet next_dot is used in an if statement, why?
def on_mouse_down(pos):
if dots[next_dot].collidepoint(pos):
if next_dot:
lines.append((dots[next_dot - 1].pos, dots[next_dot].pos))
next_dot = next_dot + 1
else:
lines = []
next_dot = 0
I do not understand what "if next_dot:" does and how it contributes to this code.
In python, a variable is "falsy" or "truthy", which means when an "if" statement evaluates the variable as an expression, it will give either false or true. Falsy variables are for example empty strings, empty lists, zero, and none, while truthy are those with values, for example [1,2,3] or 'foo'.
if 0:
# this code will never run
if []:
# this code will never run
if 1:
# this code will always run
Since you do not want to run that function if next_dot is 0, because then you would get a negative index, he put an if statement.
Welcome to Stack Overflow! For numbers, 0 will always evaluate to False. Everything else will evaluate to true. Also, because it is a number it can be incremented and the code inside the if block can be executed a precise number of times.
This question already has answers here:
What does "while True" mean in Python?
(18 answers)
Closed 4 years ago.
So, I'm learning Python through a series of videos on YT and this time, while loops are being covered. The exemple code is thus:
given_list2=[5,4,4,3,1,-2,-3,-5]
total3=0
i=0
while True:
total3+=given_list2[i]
i+=1
if given_list2[i]<=0:
break
print(total3)
Running the script, I get 17 as a result. Then, experimenting with the code, I exchanged True for False as thus:
given_list2=[5,4,4,3,1,-2,-3,-5]
total3=0
i=0
while False:
total3+=given_list2[i]
i+=1
if given_list2[i]<=0:
break
print(total3)
And it gives me 0 as a result. I'm trying to understand why that's the case. Like, what is it being considered True that keeps running the code, and what is being considered False that it fails to even initialize the code?
The reason why the answer is 0 is because while False means that the body of the loop is not going to be executed even a single time, and since total3 is only incremented in the body loop, its value is going to stay the same as before the loop, which is 0 because of total3=0 line above it.
In order for the loop body to execute the value of the expression after while should be truthy. The most common truthy value is True.
A while loop evaluates a condition and executes the code in its block when the condition evaluates to True, otherwise it exits the loop. The condition True causes the loop to continue infinitely since it can only ever evaluate to True, while False causes the loop to immediately exit without running the code in its block.
I know this is only an example of how to use a while loop, however, had this been an actual use case you'd want to use a for loop instead.
given_list2 = [5, 4, 4, 3, 1, -2, -3, -5]
total3 = 0
for n in given_list2:
if n > 0:
total3 += n
else:
break
print(total3)
or even
total3 = sum(n for n in given_list2 if n > 0)
True and False are boolean literal values. That is, their values are known and set by the language. Imagine if you had something like:
while 1 < 2:
The "1" and the "2" are integer literal values. The expression is never changing, the results will always be the same. In this case, the result is a boolean value equal to True.
So a while loop that has "True" or any unchanging true expression, like 1 < 2, as the condition, is going to want to run "forever" because it will never fail that test. The only way to stop such a loop is to generate a keyboard exception (usually by pressing "Ctrl-C"), or to have an uncaught exception occur inside the code somewhere, or to have some piece of code execute a break statement.
In your example, you are adding up the numbers in the given_list2 and stop (by executing a break) when you encounter a negative number. So the positive numbers are summed, which is 17.
Similarly, a while loop that has "False" or any unchanging false expression as the condition is never going to run, because the very first test of while 1 > 2 will fail and the loop will abort. This results in none of the inside code being executed.
In your example, you start with total3 = 0 and never run any code, so it stays 0.
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
for i in range(2,x):
if x % i == 0:
return False
break
else:
return True
The above code is mine from codecademy's python course, and i get a prompt telling me that when 9 is passed to the argument, the function returns True instead of False. I can fix this by doing:
for i in range(2,x):
if x % i == 0:
return False
break
return True
I don't understand why the second bit of code works, and why the first bit doesn't. In fact, I would have thought the second bit of code wouldn't work: If the argument was 9, then when i == 3, x % i == 0. So the function gets a returned value of False, and the loop breaks. However, since the "return True" is NOT within the for loop, then after exiting the for loop, "return True" will execute anyway, so regardless of the input, the function will get returned a value of True, since that's the last line of code to be executed within the function?
Following that line of reasoning, I believed that my initial code would work, because if "return True" was within the for loop, then the break command would be executed (assuming the input was 9), AFTER the function has been returned a value of False. And since the "return True" line is within the the for loop, and since the break command will exit the for loop, then the last value given to the function would have been False, which would have been correct?
I apologise in advance if I have (very likely) misused certain terms, of have some flaw in my understanding of how the code works or is executed. I just can't seem to get my head around why the second bit of code works, but the first bit doesn't.
Cheers!
The for loop starts with i == 2. 9 % 2 == 1, so it goes into the else: branch, and returns True.
Only if the entire loop is run and none of the numbers divided 9 should you return True.
Also, following return ... by break is useless - the function has already returned, so that break statement is never reached.
That's also the answer to your last question -- when return is executed, this function ends. Nothing else is done anymore, and the program continues (returns to) wherever it was when it called the function.
The first version didn't work because , when ever the if condition is false it returns True.Thus, when x==9 and i==2, 9%2!=0, thus it returns true. Also, no need to use break statement as return statement returns the value from function and loop doesn't continue after return.
Following is the correct code
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
for i in range(2,x):
if x % i == 0:
return False
return True