gpt4 book ai didi

python - 在 python 中给出负数时使程序计数

转载 作者:行者123 更新时间:2023-12-04 07:45:24 26 4
gpt4 key购买 nike

我需要让这段代码以这种方式工作。当给出负数时 (-3) 它应该向上计数-3, -2, -1, 0, 发射!
该代码仅从正数倒数到 0,当给出负数时,它仅打印“Blastoff!”
我最初的想法是在第二个函数中将“<”更改为“>”,但没有' do anything.
此外,我需要以这样一种方式进行设置:当我输入 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()

最佳答案

去掉countup中的for循环,保证传入负数。

请注意,这里的 range 方法并没有按照您的预期进行:

>>> 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!

关于python - 在 python 中给出负数时使程序计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67223397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com