What Is Function With Yield And Return In Python?

Asked 8 months ago
Answer 1
Viewed 184
1

It is by and large used to change over a customary Python capability into a generator. A generator is an extraordinary capability in Python that profits a generator object to the guest. Since it stores the neighborhood variable states, consequently above of memory designation is controlled.

Example:

# Python3 code to demonstrate yield keyword 
  
# Use of yield
def printresult(String) : 
    for i in String: 
        if i == "e": 
            yield i 
  
# initializing string 
String = "GeeksforGeeks" 
ans = 0
print ("The number of 'e' in word is : ", end = "" ) 
String = String.strip() 
  
for j in printresult(String): 
    ans = ans + 1
  
print (ans) 

Output:

The number of 'e' in word is : 4

Python Return

It is by and large utilized for the finish of the execution and "returns" the outcome to the guest explanation. It can return all kind of values and it returns None when there is no articulation with the assertion "return".

# A Python program to show return statement 
class Test:  
    def __init__(self):  
        self.str = "GeeksForGeeks"
        self.x = "Shubham Singh"   
      
# This function returns an object of Test  
def fun():  
    return Test()  
          
# Driver code to test above method  
t = fun()   
print(t.str)  
print(t.x) 

Difference between Python yield and Return

S.NO. YIELD RETURN
1 Yield is for the most part used to change over a standard Python capability into a generator. Return is by and large utilized for the finish of the execution and "returns" the outcome to the guest articulation.
2 It replace the return of a function to suspend its execution without destroying local variables. It exits from a function and handing back a value to its caller.
3 It is used when the generator returns an intermediate result to the caller. It is used when a function is ready to send a value.
4 Code written after yield statement execute in next function call. while, code written after return statement wont execute.
5 It can run multiple times. It only runs single time.
6 Yield statement function is executed from the last state from where the function get paused. Every function calls run the function from the start.

 

Answered 8 months ago Thomas Hardy