简体   繁体   中英

why does my program return None in for loop?

I have a function that should print the squares in the given interval:

class Squares:

    def __init__(self, min, max):
        self.min = min
        self.max = max

    def __iter__(self):
        return self

    def __next__(self):
        a_list = []
        for i in range((self.max)+1):
            a_list += [i**2]

        if self.min <= self.max:
            if self.min in a_list:
                result = self.min
                self.min += 1
                return result
            else:
                self.min += 1

        else:
            raise StopIteration

import math

for i in Squares(5, 50):

    print(i) 

It should print 9, 16, 25, 49, but the output was:

None
None
None
None
9
None
None
None
None
None
None
16
None
None
None
None
None
None
None
None
25
None
None
None
None
None
None
None
None
None
None
36
None
None
None
None
None
None
None
None
None
None
None
None
49
None

Why is this?

The reason that None is returned every time the variable result is not a perfect square, is that the next() function returns None by default if no return is specified.

If you must use an iterator for this project, you have to structure your code so that a value is returned each pass.

Also, notice that each time next() is called, an entirely new array named a_list is generated, which is pretty inefficient. It would be much better to initialize that array once.

Check out the differences in this example.

class Squares:

def __init__(self, min, max):
    self.min = min
    self.max = max

def __iter__(self):
    self.a_list = []
    for i in range((self.max)+1):
        self.a_list += [i**2]
    self.iter_index = 0
    return self

def next(self):
    self.iter_index += 1
    if self.a_list[self.iter_index] > self.max:
        raise StopIteration
    else:
        return self.a_list[self.iter_index]

import math
import pdb

for i in Squares(5, 50):
    print(i) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM