Python循环N到0或-N到0

时间:2019-02-28 06:04:22

标签: python python-3.x loops scripting

We will pass in a value N. N can be positive or negative.

If N is positive then output all values from N down to and excluding 0.
If N is negative, then output every value from N up to and excluding 0.

我对这个挑战感到困惑,我不知道该如何编码,或者只输出正值或负值。

有帮助吗?

1 个答案:

答案 0 :(得分:0)

能否请您检查此代码,并让我知道它是否有效。

def printNumber(num):
    #If N is positive then output all values from N down to and excluding 0.
    if num > 0:
        for i in range(num, 0, -1):
            print(i)
    #If N is negative then output all values from N up to and excluding 0.
    else:
        for i in range(num, 0):
            print(i)

printNumber(-5)
printNumber(5)