I am learning python programming for backend and I had the assignment of writing a for loop for the menu below. The program ultimately subtotals, adds tax and then totals the cost (rounded to two decimal places). However, I was stumped when it was time to put in action what I had learned. I understand everything but how I should write the for loop. Another student came up with the below for loop which was correct, but it was not the way we were taught to do it.
He came up with this for loop
addUp = sum(s['price'] for s in order if s)
I want to understand this because it is apparently a shorthand for loop. I asked him what he did and he couldn't explain it, because he had taken the answer from stack overflow. I can't keep this as something I know when I don't understand it. Can someone please explain that portion of the code.
I know that 'price' is the key and its being summed. Is 's' a new variable temporarily holding price? and why does it end in "if s" ? I really dont get it. Because I am a beginner it would probably be easier for me to understand if I can see the "long-hand" version of this for loop.
I think my confusion comes from initially learning to write for loops to access a list instead of a dict. Sorry if this is a basic question but I am definitely still at the basic level of python.
I really just want to understand this before I move on. I assume we are taught this first because you have to understand it for more complex programs.
This code was correct I just don't understand it
menu = {
1: {"name": 'espresso',
"price": 1.99},
2: {"name": 'coffee',
"price": 2.50},
3: {"name": 'cake',
"price": 2.79},
4: {"name": 'soup',
"price": 4.50},
5: {"name": 'sandwich',
"price": 4.99}
}
def calculate_subtotal(order):
print('Calculating bill subtotal...')
### WRITE SOLUTION HERE
addUp = sum(s['price'] for s in order if s)
return round(add, 2)