首页 > 解决方案 > 在python中给定负数时使程序计数

问题描述

我需要让这段代码以这种方式工作。当给出负数 (-3) 时,它应该向上计数 -3、-2、-1、0,Blastoff!
代码只从正数倒数到 0,当给出负数时,它只打印“Blastoff!”
我最初的想法是在第二个函数中将“<”更改为“>”,但没有做任何事情。
另外,我需要以这样一种方式进行设置,即当我输入 0 时,它会成对计数,而不是在给出数字 0 时,它会破坏整个程序。

请帮忙,记住你是在和一个新手说话。
这是一个家庭练习练习,我已经尝试过但无法弄清楚,并且在 YouTube 或这里没有找到任何解释 python 程序的内容。

n = int(input("Please enter a number: "))
def countdown(n):
    if n <= 0:
        print('Blastoff!')
    else:
        print(n)
        countdown(n-1)
countdown(n)

def countup(n):
    for n in range(0, -100000):
        if n >= 0:
            print ( "Blastoff! ")
        else:
            print (n)
            countup (n+1)
countup(n)

def countZero(n):
    if n == 0:
        print ("You hit the magic 0 ")
    else:
        print (n)
        countZero(n+2)
countZero()                

标签: pythonif-statementconditional-statements

解决方案


删除 countup 中的 for 循环,并确保传入负数。

请注意,范围方法并没有按照您的预期进行:

>>> list(range(0, -3))
[]

如果它是负数,则需要翻转起始索引。如果您想显示零,则在 1 处停止:

>>> list(range(-3, 0))
[-3, -2, -1]

>>> list(range(-3, 1))
[-3, -2, -1, 0]

所以你可以这样做:

>>> def countup(n):
...     for n in range(n, 1):
...         if n >= 0:
...             print("Blastoff!")
...         else:
...             print(n)
...             
>>> countup(-3)
-3
-2
-1
Blastoff!

如果你想让它保持递归,那么你根本不需要循环:

>>> def countup(n):
...     if n >= 0:
...         print("Blastoff!")
...     else:
...         print(n)
...         countup(n + 1)
...         
>>> countup(-3)
-3
-2
-1
Blastoff!

奖励 如果您想要一种方法来处理向上计数和向下计数,请使用另一个if/else语句:

>>> def blastoff(n):
...     if n == 0:
...         print("Blastoff!")
...     else:
...         print(n)
...         if n > 0:
...             blastoff(n - 1)
...         else:
...             blastoff(n + 1)
... 
>>> blastoff(3)
3
2
1
Blastoff!
>>> blastoff(-3)
-3
-2
-1
Blastoff!

推荐阅读