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.
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/
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
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.
I have a really basic if/else logic question for Python. An exercise in the book required me to write a function that takes a list of integers are returns True if the list contains all even numbers and False if it doesn't.
I wrote:
list1 = [8,0,-2,4,-6,10]
list2 = [8,0,-1,4,-6,10]
def allEven(list):
for x in list:
if x % 2 != 0:
return False
else:
return True
This code always returns True. Why is that? Doesn't the code see the -1 during the loop of all the values of the list and returns the False?
list1 = [8,0,-2,4,-6,10]
list2 = [8,0,-1,4,-6,10]
def allEven(list):
for x in list:
if x % 2 != 0:
return False
return True
The book gives the answer of this. Why does this work and mine doesn't?
Pay close attention to where that else is placed. Indentation and nesting matters here!
In your first example, it will return True on the first element that satisfies your condition because your first if check fails.
In your second example, it will return True after all elements have been iterated through and a return value hasn't been produced.
The first function checks the first number only, since it returns something as soon as the for loop starts.
By the way, you can but should not use list as an argument or a variable name, since it is a keyword.
I strongly recommend writing a print statement to output x before both of your return statements. It will help you understand the flow of the code.
The short answer is that only the first element is being checked by your code, and the function returns True or False based on that value.
In the book solution, any failure causes a return of False, but the loop simply continues otherwise. Only if all elements are checked without failure does the return True reached.
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