【发布时间】:2020-05-18 06:45:34
【问题描述】:
这段代码有什么问题 每次向上或向下计数时都会添加额外的行 我该如何防止这种情况以及为什么会发生这种情况?
def counter(start, stop):
x = start
if start > stop:
return_string = "Counting down: "
while x >= stop:
return_string += str(x)
x = x-1
if start != stop:
return_string += ","
print(return_string)
else:
return_string = "Counting up: "
while x <= stop:
return_string += str(x)
x = x + 1
if start != stop:
return_string += ","
print(return_string)
return return_string
print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1)) # Should be "Counting down: 2,1"
print(counter(5, 5)) # Should be "Counting up: 5"
【问题讨论】:
-
“每次向上或向下计数时添加额外的行”。每次循环打印。你看他们有关系吗?
-
只需删除函数中的
print语句。您可能还想return return_string.rstrip(',')修剪尾随逗号。
标签: python for-loop while-loop counter