Friday, July 1, 2022

Generator to print even numbers (yield in Python)

(.env) boris@boris-All-Series:~/VOTING/ADABOOST$ cat EvenGenerator.py

# Python3 code to demonstrate

# yield keyword

# generator to print even numbers

def print_even(test_list):

    for i in test_list:

        if i % 2 == 0:

            yield i

# initializing list

test_list = [1, 4, 5, 6, 7]

# printing initial list

print("The original list is : " + str(test_list))

# printing even numbers

print("The even numbers in list are : ", end=" ")

for j in print_even(test_list):

    print(j, end=" ")

print("\n")

(.env) boris@boris-All-Series:~/VOTING/ADABOOST$ python3 EvenGenerator.py

The original list is : [1, 4, 5, 6, 7]

The even numbers in list are :  4 6














(.env) boris@boris-All-Series:~/VOTING/ADABOOST$ cat EvenGenerator1.py

def mygenerator(n):

   for i in range(1, n, 2):

      yield i**3

for i in mygenerator(10):

    print(i)

(.env) boris@boris-All-Series:~/VOTING/ADABOOST$ python3 EvenGenerator1.py

1

27

125

343

729



















No comments:

Post a Comment