available_items = {"health potion": 10, "cake of the cure": 5, "green elixir": 20, "strength sandwich": 25, "stamina grains": 15, "power stew": 30}
health_points = 20
health_points += available_items.pop("stamina grains")
When I run this code the value of key "stamina grains" is added and stamina grains is removed from the dictionary available_items
.
But Python evaluates expressions left to right so it should remove the key "stamina grains" first therefore there should be nothing added to the health_points
.
I am confused on how Python evaluates expressions. Could someone clarify it and also give me some resources about how Python evaluates expressions?
If you look here: Operator precedence , you can see that "call" is near the bottom of the table, so this is executed first. After execution of this first step, you could rewrite the statement as:
health_points += 15
.
A little higher is addition, which is executed next (+=
is short for addition: health_points = health_points + available_items.pop("stamina grains")
). And at the top is assignment, so this is executed last. Resulting in health_points == 35
.