【发布时间】:2020-09-11 08:10:20
【问题描述】:
对于学习 Python 的练习,我尝试制作一个 float_range() 迭代器,它模仿 range() 但允许浮点数。我尝试捕获错误数量的参数来引发 TypeError 并编写下面的函数。
def float_range(*args):
start = 0.0
step = 1.0
if len(args) == 3:
start, end, step = args
elif len(args) == 2:
start, end = args
elif len(args) == 1:
(end,) = args
else:
raise TypeError()
n = start
if start < end:
if step > 0:
while n < end:
yield n
n += step
else:
if step < 0:
while n > end:
yield n
n += step
现在,我不明白为什么 for n in float_range(1,2,3,4): print(n) 和 for n in float_range(): print(n) 会引发 TypeError,但 float_range() 和 float_range(1,2,3,4) 不会。
【问题讨论】:
-
您是否尝试过使用调试器单步执行代码以查看每种情况下会发生什么?
标签: python-3.x iterator typeerror