This is a question regarding assignment #2, Q3: Could someone please explain to me the syntax in this set of code: def can_buy(n, ax, bx, cx): for a in range(0,20): for b in range(0,20): for c in range(0,20): k = ax * a + bx * b + cx * c if k == n: return True return False My question is which loop does "return False" and "return True" fall into? And does the loop end up with a False every time it is run?
Python relies on indentation to check for block statements. Therefore, the first return will return true if and only if k == n. That should fall into the last loop (for c in range (0,20)), because the condition to execute it is tested every time c is tested, while the other (return False) will be executed only after all 3 loops are done. Also, note that return ends the execution of the function, "returning" something (True/False) to the caller of the function.
Thank you for your reply bmp. I understand the part where it says if k == n, "True" will be returned. I have 2 more questions: 1) For the 'return False' part, does it mean that if the condition of k == n is not met after the nested loops are completed, False will be returned? 2) And you says that return ends the function, so does that mean if 'True' is returned, the function will be stopped at that point and 'return False' will not be run?
For the 2), yes. Try something like: def foo(): return 'yay' print 'bar' 'bar' will never be printed. As for 1), think about it this way: False will be executed if and only if k is never equal to n, during the execution of all 3 loops. If k == n, return True will be executed and the function ends.
Got it! Thank you!!
Join our real-time social learning platform and learn together with your friends!