Calculating a total within a loop

Hey, I’m trying to get it to times the price by how much stock, and print the values, but it’s not working, any help would be great

Check the indentation.
The function definition should not be inside the loop.

There’s a scope issue:
total (as a number) is declared inside a function, so it is not accessible outside of the function.

You can fix that by having return total inside the function, but outside the loop in the function.

for key in prices:
  print key
  print "price: %s" % prices[key]
  print "stock: %s" % stock[key]

def total():
  total = 0
  for key in prices:
    print prices[key] * stock[key]
    total = total + prices[key]*stock[key]
  #print total
  return total

print total()  # not in a loop

Notice that last line is a function call.

(You created a function called total instead of a variable that holds a number.)

Note that you don’t need to create a function to do this pat of the exercise.

1 Like