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) .
Related
Code
def addition(num):
if num:
return num + addition(num - 1)
else:
return 0
res = addition(10)
print(res)
Explanation
I know what the function is doing:
it is a recursive function
I just don't know what if num: means or the else part.
I am guessing it means as long as the num is int do what is inside the if, else return 0.
Question
Can someone tell me what this code means?
if variable: and truthyiness
See the boolean values and Python's Truth Value Testing:
What is Truthy and Falsy? How is it different from True and False?
You can evaluate truthy and falsy values using the bool() conversion-function:
print('None:', bool(None))
print('zero:', bool(0))
print('negative:', bool(-1))
print('positive:', bool(1))
if num: mets if num is defined and unequal to 0:
is defined: num is not None
and is not zero: num != 0
bool(0) is False. The opposite condition is tested by if not num.
The role of if in a recursive function
It's a recursive function which calls itself until exit-condition num == 0 is met in the else branch. Then it simply returns 0. So, the role of if num: is the continue-condition opposed to an exit-condition.
You could also write it as exit-condition:
def addition(num):
if not num: # equivalent to: if num == 0 or num is None
return 0 # return 0 if exit-condition met
# default behavior: recurse until zero met
return num + addition(num - 1)
See also:
recursive factorial function
Basics of recursion in Python
Edge-cases for input
Note, how input of None and other falsy values return a zero.
Please also consider the edge-case of negative input, as Fred commented. Could (silently) return 0 to abort addition. Also might raise an error to warn about misuse, like:
if num < 0:
raise ValueError("Can not calculate the recursive-sum for negative values.")
What happens if a float like 10.5 is given as input?
It would step through each -1 decrease until 0.5. The next call of addition(-0.5) would jump over the num == 0 exit-condition and cause infinite recursion, even a stackoverflow.
Python and many other languages have a concept of "falsy", which roughly means "values that are treated as False when evaluated as a boolean". In Python, values that are falsy include empty collections such as empty lists, strings, sets, tuples, and dicts, the int or float 0, and None. I may be missing some here, and you may find that some classes are designed to be treated as falsy as well under certain conditions. There are also "truthy" values which evaluate to True is a boolean context. It's easy to find out if a value is truthy or falsy. Simply call bool() on it:
bool(0.0)
# False
In the context of your code, when 0 is reached, that will be evaluated as falsy, triggering the exit condition.
if num: means if num is different than 0 : if num!=0.
you better remove the else statement.
def addition(num): if num: return num + addition(num - 1) return 0
python already knows that return is an else statement.
here's a playlist of one of the bests on youtube by corey to learn & become at python : https://www.youtube.com/watch?v=YYXdXT2l-Gg&list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7
and also I recommend this book, automating the boring stuff with python. it's free : https://automatetheboringstuff.com/
Which code segment should replace the statement pass in the function hasEvenNumber which returns True if n contains an even number and False otherwise?
def hasEvenNumber(n):
for i in n:
pass # Replace this section with below options
return result
The question screenshot
This is an actual university exam question. I find it very badly structured and since my classmates are new too, nobody dared to voice out fearing to make a fool of themselves.
Firstly n was not given, but judging that n will be used in a for loop. n therefore, would be an iterable. I think none of the 4 options applies, but please advise me if I'm wrong.
Option 1:
if i % 2 == 0:
result = True
else:
result = False
This will only work if iterable only contains 1 item e.g [1,2,1] will not work since the result of 2 as even number that should return true will be replaced as the loop proceed to next iteration.
[1,2,1,1] False # Wrong, should be true
[1,1,1,2] True
[2] True
Option 2:
if i % 2 == 0:
result = True
break
else:
result = False
break
Worse than above, this will only iterate the first item and break regardless.
[1,2,1,1] False # Wrong, should be true
[1,1,1,2] False # Wrong, should be true
[2] True
Option 3:
if i % 2 == 0:
result = True
break
Function will have runtime error if no even number is found, the variable result will not be assigned.
[1,2,1,1] True
[1,1,1,1] Runtime Error
[2] True
[1] Runtime Error
Option 4:
if i % 2 != 0:
result = False
break
Same as above, runtime error. No variable will be assigned if all even numbers.
Personally, as the question asked to check if n contains even number. I would have written something like this.
# Break and exit loop once even number is found. Otherwise continue.
if i % 2 == 0:
result = True
break
else:
result = False
Unfortunately, this is not an option. Apologies if this is the wrong place to post this, but any advice would be gladly appreciated, and could possibly change the fate our my current school cohort.
Yes, you are right and little bit overthinking.
Third option is right and it is kinda assumed here that result is set to False in the beginning.
Also, your solution can be optimised by declaring result = False once in the beginning and then you can eliminate the else block completely.
If you want it to end when an even number is found, option 3.
Code from "Think Like a Computer Scientist: Python"
def find(astring, achar):
ix = 0
found = False
while ix < len(astring) and not found:
if astring[ix] == achar:
found = True
else:
ix = ix + 1
if found:
return ix
else:
return -1
I've run this through CodeLens in all variations of location of not and original value for found, but cannot wrap my head around the way Python handles its conditions in this form. Please point out where my train of thought goes wrong or what I miss:
If found = False, then not found = True when found = True.
The condition is set to not found so the loop will iterate. (I set the condition to found and it does not iterate. So while loops must only iterate for True values). Once achar is found in astring, found = True. What is the logic behind this closing the loop? Where is my misunderstanding of the use of not?
I think you should consider the Not operator as an inverter. The logic table would be:
A | Not A
T | F
F | T
So when Found is False it is actually True and when it is True it is False.
The conditional statement for the while loop works as while True - execute code, while false exit code.
Looking at the conditional, it is an and operation where both operations have to be True to be True, if you look up the and gate truth table you can learn more about it.
Basically, both 'ix < len(astring) and not found' have to be true for the loop to.
Hope this helps
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
# 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.