python - 在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()
解决方案
删除 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!
推荐阅读
- azure - Azure 容器实例 - 公开端口以绑定 443 (HTTPS)
- sql - 使用查询完成sql同步
- multithreading - 哪个更有效:多线程程序中的 curl_easy_perform() 或单线程程序中的 curl_multi_perform()?
- r - 用 R 中的彩色单元格绘制表格
- amazon-s3 - 使用额外参数 AWS S3 访问私有文件
- php - 在php中制作自动回复
- qt - qmake 不复制文件(安装)
- php - PHP将字节数组作为字符串转换为pdf
- c++ - 如何将 QByteArray 转换为 std::istream 或 std::ifstream?
- c++ - 如何更改 unordered_map 中的键?