我正在尝试python范围函数的两个变体,其主要目标是使函数具有包容性。然而,似乎都没有工作
def main():
for i in standard_range(1, 25, 1):
print(i, end='')
def inclusive_range(*args):
numargs = len(args)
if numargs < 1:
raise TypeError("Requires atleast one argument")
elif numargs == 1:
stop = args[0]
start = 0
step = 1
elif numargs == 2:
(start, stop) = args
step = 1
elif numargs == 3:
(start, stop, step) = args
else:
raise TypeError("Cannot have more than three arguments")
i = start
while i <= stop:
yield i
i += step
def standard_range(start, stop, step):
i = start
while i <= stop:
yield i
i += step
if __name__ == " __main__ ":
main()
任何帮助将不胜感激。
答案 0 :(得分:1)
如果这是您的确切代码,则main()
无法运行,因为__main__
之前和之后都有空格:
if __name__ == " __main__ ":
main()
删除空格:
if __name__ == "__main__":
main()
standard_range
不应打印停止值,因此请使用<
代替<=
:
while i < stop:
如果我进行了这些更改,请使用此主要内容:
def main():
print(*standard_range(1,25,1))
print(*inclusive_range(1,25,1))
结果是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25