Reputation: 190
I have some code that is basically a demo for how dict
works. My problem is, I am not sure exactly when it is calling the process_order()
function. It seems like the main loop (go_shopping
) never calls it, but the script seems to work. The go_shopping
function calls get_item
, but that doesn't call process_order
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 process_order
? 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?
Code:
#!/usr/bin/python3.5
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]
else:
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')
break
print ('while loop end')
print (cart)
print ("Finished!")
go_shopping()
Upvotes: 0
Views: 54
Reputation: 16710
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.
Upvotes: 2