New course! Every coder should learn Generative AI!
Try a free lesson0
facing difficulty to print out the iteration
it's showing that 'nonetype object is not iterable', why? If you have solution please help me to solve out. thanks def if_primes(): num = 2 def is_prime(num): #defined it by myself while True: if is_prime(num): yield num num += 1 for num in if_primes(): print(num) https://sololearn.com/compiler-playground/cz3V8Wl4rLH7/?ref=app
3 Answers
+ 3
I think you mean 'NoneType' object is not iterable.
If you defined a function but not specify the return value, None will be returned.
In your if_primes() function, there is no return value.
Therefore line 9 becomes:
for num in None:
Since None, a 'NoneType' object, is not iterable, you get the error message.
You can add return num in line 8 for your if_primes() function, and you will see the error message change accordingly.
+ 1
In this case, the if_primes() function creates a generator object, and it returns 5, 4, 3, 2, 1. You can test it with the code below:
x = if_primes()
print(type(x)) # <class 'generator'>
next(x) # 5
next(x) # 4
next(x) # 3
next(x) # 2
next(x) # 1
next(x) # error, StopIteration
You can think of it similar to range(5).
Unlike return, yield not only return a value to its caller, but also keep the code running. So it does "returning" a value without a "return" keyword.
In your previous example, the yield is returning a value to itself (is_prime() function), but it doesn't have a specific return value to its caller if_primes() method. Therefore if_primes() return None to its caller: line 9.
0
thanks for your reply but what about this one...?
def if_primes():
i = 5
while i > 0:
yield i
i -= 1
for i in if_primes():
print(i)
here you write any return for the if_primes() function?