Python – Fixing SyntaxError: ‘return’ with argument inside generator
This error is telling you that when you use a yield inside of a function making it a generator, you can only use return with no arguments.
This makes sense because return raises a StopIteration error in a generator and it would be quite unexpected to be getting values back with that.
Here is how you can accomplish what you need to do though:
Say you want to do this:
def f():
for i in range(2):
yield i
return i+2
You can do this instead and probably get a result close enough to what you want:
def f():
for i in range(2):
yield i
yield i+2
return
You can even remove the “return” statement in the second example, it is not needed at all.
Jonathan, you are correct. I wanted to include it to show how a return in a generator would look in case you’re doing something more complex. For example wanting to return from inside a loop at a certain point.