While loops in Python 3 and True/False conditions [duplicate] - python

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.

Related

wondering why my list has bigger number than second argument function return False?

def greater(list, num)
for x in list:
if x > num:
return True
else:
return False
as you can see in my code, i am trying to write a function that return True if list_number contained number that is bigger than second argument, otherwise return False.
but here is confusing:
when i input: greater([1, 2, 3], 2), and its return False. I am wondering why is that? the first argument contained 3 and its bigger than 2.
any helps and explanations will be appreciated.
You want to have it return at the end of the function. Right now, you have it return after checking only the first number. Try this:
def has_gt(list_number,number):
for x in list_number:
if x > number:
return True
return False
A property of if/else is that if one runs, the other doesn't. But in both cases, one runs. In your code, this snippet:
if x > number:
return True
else:
return False
Means that it will check if the number is bigger than the number in question. If it is, it will return True. If not, it will return False. A return call instantly ends the processing of a function, so it will stop checking after that.
To summarize, your code loops through the target list. It checks the first number, one, and sees if it is bigger than two. It is not, so the code returns False, instantly ending the function. So, your function just ended in a False, which is what it returned.
The change I made was that it returns False at the end of the code. This means that it will check each value for being greater than the target. If it finds any value greater than the target, it will end processing, with a return value of True. If the code hasn't returned by the time it reaches the end of the function, it will return False because of the statement at the end of the function.
Actually what happens is the else part also runs just after comparing the number (here 2) with the first element in the list_number (here 1) thus returns false.
So the solution is you need to let the for loop first run completely which is stopped by the else statement.
def has_gt(list_number,number):
for x in list_number:
if x > number:
return True
return False

Why is an integer variable used in an if statement?

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.

Can someone tell me why this while loop works in python? [duplicate]

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 5 years ago.
sum, Nr = 0, 12
i = Nr
while i:
sum += i
i -= 1
print ('The sum of all natural numbers up to (and inclusive of) ' + repr(Nr) +
' is ' + repr(sum))
So this is a very simple while loop in python 3 which returns "The sum of all natural numbers up to (and inclusive of) 12 is 78" as expected.
What I am confused about is that why this condition "while i:" works here when "i" is not subjected to any comparison operator.
Thanks!
In conditional statements, the input is implicitly cast to boolean, hence the loop is equivalent to
while bool(i):
...
bool(i) is True as long as i != 0, and False if i == 0, so the loop goes until i becomes zero.
While expect the expression and if it is true is runs the loop.
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
In [38]: bool(Nr)
Out[38]: True
while loop expects any condition either True or False. When you write while i (suppose i = 5) it is evaluated as True, so the loop continues but when it encounters i=0 it is evaluated as False and the loop breaks.
It seems that Python does an implicit replacement with i not equals zero (pseudo code). See documentation.
Python automatically computes the truthy value of the variable passed to it by converting it into boolean. Since i being a non-zero positive integer is considered true in Python, that's why it's working, till it finally becomes 0 which is considered false.
>>> print(bool(3))
True
>>> print(bool(0))
False
In python, values are duck typed - what this means is that the interpreter can try to fit the value into whatever context you have put it. All numbers other than zero are 'truthy', so for instance
if 3: # True
Whereas zero is falsy:
if 0: # False

Error when trying to return True/False values to a definition in python

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

While loop assignment

# 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.

Categories

Resources