The way I see it, you did not give any initial value to d. So Python is saying "Yeah, I'm adding 1 to WHAT ?". Python does not even know what type d is if you don't initialize it. Simply add d = 0 at the beginning of your code.

It seems that you're having a bit of confusion in 'nested' loops (probably)

I presume python nested loops works as any other programming language. eg: first the outer loop executed once, then executes the inner until it finishes or finds a condition, the again the outer loop again.... isn't it right?

As I can see from your code you've got a 'for' loop which you you want the var 'd' to increment.

Then you're using a 'while' loop.
and you've alredy told us that 'd' is being initialise somewhere in your code. OK...
let's see now, I think there's something wrong in the while 'loop' condition....