0
私は一定の間隔で正方形を印刷する必要がある機能を持っている:なぜ私のプログラムはforループでNoneを返すのですか?
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)
それは9、16、25、49を印刷する必要がありますが、出力された:
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
これはなぜですか?
内部の 'else:'ブロックからは何も返されませんか? –
番号がリストにない場合は、返却する必要はありません。 –
イテレータは次の値を返す必要があります。それがなければ、あなたは現在あなたが見ているものを得る。したがって、コードをa)正方形だけを含むリストを生成するか、またはb)正方形でない値をスキップするように変更します。 –