I have recently been experimenting with python generators a bit, and I came across the following curious behaviour, and I am curious to understand why this happens and what is going on:
def generating_test(n):
for a in range(n):
yield "a squared is %s" % a*a # Notice instead of a**2 we have written a*a
for asquare in generating_test(3):
print asquare
Output:
a squared is 1
a squared is 2a squared is 2
Versus the following script which generates the expected output:
def generating_test(n):
for a in range(n):
yield "a squared is %s" % a**2 # we use the correct a**2 here
for asquare in generating_test(3):
print asquare
Output:
a squared is 0
a squared is 1
a squared is 4
This doesn’t have anything to do with generators:
The
%op is performed before the multiplication, using the string and the firstaas arguments. Youra**2works because the**op withaand2as arguments is evaluated before the%.