【发布时间】:2018-07-09 16:51:16
【问题描述】:
我有一个模仿 range() 的函数。我被困在某一时刻。我需要能够使第一个 (x) 和第三个 (step) 参数可选,但中间 论点 (y) 强制性的。在下面的代码中,除了被注释掉的两行之外,一切正常。
如果我只传入一个参数,我如何构造函数以接受传入的单个参数作为强制 (y) 参数?
我不能这样做:def float_range(x=0, y, step=1.0):
非默认参数不能跟随默认参数。
def float_range(x, y, step=1.0):
if x < y:
while x < y:
yield x
x += step
else:
while x > y:
yield x
x += step
for n in float_range(0.5, 2.5, 0.5):
print(n)
print(list(float_range(3.5, 0, -1)))
for n in float_range(0.0, 3.0):
print(n)
# for n in float_range(3.0):
# print(n)
输出:
0.5
1.0
1.5
2.0
[3.5, 2.5, 1.5, 0.5]
0.0
1.0
2.0
【问题讨论】:
-
我的问题是只传入一个参数。在上面的代码中,我唯一无法工作的行是注释掉的行。
标签: python-3.x function python-3.6