首页 > 解决方案 > Python 循环 N 到 0 或 -N 到 0

问题描述

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.

我被困在这个挑战中,我不知道如何编码或只输出正值或负值。

有什么帮助吗?

标签: pythonpython-3.xloopsscripting

解决方案


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

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)

推荐阅读