计数器向上或向下脚本不工作 python

新手上路,请多包涵

我正在尝试创建一个脚本,如果开始 < 停止或倒计时是开始 < 停止则计数。我得到了部分输出但不是全部。有小费吗?

 def counter(start, stop):
x = start
if x > stop:
    return_string = "Counting down: "
    while x > stop:
        return_string += str(x)
        if x == stop:
            return_string += ","
        return return_string
else:
    return_string = "Counting up: "
    while x <= stop:
        return_string += str(x)
        if x == stop:
            return_string += ","
        break
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"

原文由 inkblot 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 598
2 个回答

你犯的一些错误:

  1. 您已经 break 第一次迭代的循环
  2. 只有在到达停止时才添加逗号,这正是不再需要逗号的时候
  3. if x == stop 永远不可能为真,因为封闭循环的终止条件 while x > stop
  4. 出于同样的原因, stop 本身永远不会添加到输出中

以下更改将修复您的功能:

 def counter(start, stop):
    x = start
    if x > stop:
        return_string = "Counting down: "
        while x > stop:
            return_string += str(x)+","
            x -= 1
    else:
        return_string = "Counting up: "
        while x < stop:
            return_string += str(x)+","
            x += 1
    return_string += str(stop)
    return return_string

>>> counter(1,2)
'Counting up: 1,2'
>>> counter(1,5)
'Counting up: 1,2,3,4,5'
>>> counter(5,1)
'Counting down: 5,4,3,2,1'
>>> counter(5,2)
'Counting down: 5,4,3,2'

原文由 user2390182 发布,翻译遵循 CC BY-SA 4.0 许可协议

这对我有用

def counter(start, stop):
x = start
if x>stop:
    return_string = "Counting down: "
    while x >= stop:
        return_string += str(x)
        if x!=stop:
            return_string += ","
        x-=1
else:
    return_string = "Counting up: "
    while x <= stop:
        return_string += str(x)
        if x!=stop:
            return_string += ","
        x+=1
return return_string

原文由 Jean Mitchelle 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进