+ 2
Yield
yield=return or it has some differents
3 ответов
+ 7
yield and return are different things. As soon as a function returns a value, the function is dead, all local variables are lost and if you want to access the function again, you have to call it again. Basically, a function cannot return more than one value.
def sum(a, b):
return a + b
Here, the sum of a and b is returned and the function is done.
Yield can give you dozens, hundreds or thousands of results, but it will only give you one result at a time and then it "freezes" until the next value is called.
For example, you could use it like this:
def getPrimeNumbers():
for i in range(1000000):
if isPrime(i):
yield i
This will create a generator object. Although it is made to check for all prime numbers in a huge range of numbers(0-999999), it will only give you one prime number at a time and then it will wait until you ask the function to give you the next prime number. So you need some kind of functionality to call the generator function and "receive" each prime number. It could look like this:
print(next(getPrimeNumbers()))
# ouput: 2
print(next(getPrimeNumbers()))
# ouput: 3
print(next(getPrimeNumbers()))
# ouput: 5
print(next(getPrimeNumbers()))
# ouput: 7
With next(), you get the next result of the generator. You can do this as long as the generator generates output.
Or you could do it like this:
for n in getPrimeNumbers():
print(n)
or
print(*getPrimeNumbers())
This will print all prime numbers at once (of course this will need a function isPrime() to work).
+ 1
https://code.sololearn.com/cRPCsJjBMvDv/?ref=app
Yiel key word create generators (search on internet, it's better, I'm a so bad teacher 😥), while return returns à value.
It's hard to teach, sorry...
0
It has some differents. I will share you a code to show you how different it is...