arcesso arcesso - 2 months ago 13
Python Question

Logic and calling functions. Help me understand this code

I have some code that is basically a demo for how

works. My problem is, I am not sure exactly when it is calling the
function. It seems like the main loop (
) never calls it, but the script seems to work. The
function calls
, but that doesn't call
either. I am also having trouble with the line
if not process_order(order, cart):
. What does the
if not
part mean in this case? Is that where it is calling
? It doesn't seem like it from the print statements, other wise it should print 'if not' when you add an item to the cart dictionary object.

Am I on the right track or missing something simple?



def get_item():
print("[command] [item] (command is 'a' to add, 'd' to delete, 'q' to quit.)")
line = input()

command = line[:1]
item = line[2:]

return command, item

def add_to_cart(item, cart):
if not item in cart:
cart[item] = 0
cart[item] += 1

def delete_from_cart(item, cart):
if item in cart:
if cart[item] <= 0:
del cart[item]
cart[item] -= 1

def process_order(order, cart):
command, item = order

if command == "a":
add_to_cart(item, cart)
print('added to cart')
elif command == "d" and item in cart:
delete_from_cart(item, cart)
elif command == "q":
return False
print ('end process_order func')
return True

def go_shopping():
cart = dict()

while True:
print ('start main loop')
order = get_item()
print ('exited process_order')
if not process_order(order, cart):
print ('if not')
print ('while loop end')
print (cart)
print ("Finished!")



Thing is, I am not really sure of your problem. But you seem concerned with the moment when process_order method is called.

When you write

if not process_order(order, cart)

it must be seen as follows (just adding parentheses):

if (not process_order(order, cart))

So you're asking Python to do something if the condition not process_order(order, cart) is true. So, Python must know the boolean value of the expression not process_order(order, cart).

This expression is composed of a unary operator, not, and a non-elementary expression, process_order(order, cart). That latter expression needs to be evaluated, so Python has to run the process_order method.

Therefore, when you write if not process_order(order, cart), the process_order method is indeed executed.