python - 一个 while 循环来向上和向下计数

标签 python loops while-loop python-3.7 countdown

你如何编写一个程序来从用户整数输入开始向上和向下计数,只使用一个 while 循环而不使用 for 或 if 语句?
我已经成功地倒数了,但似乎无法弄清楚如何倒数。它也需要看起来像一个横向三角形,数字前有空格(等于打印的数字)。
到目前为止,这是我的代码;

n = int(input("Enter an integer: "))
i = " "
lines = 0
while lines <= n-1: 
    print(i * lines + str(lines))
    lines += 1

最佳答案

您可以通过充分利用负数和绝对值来解决这个问题:abs()这将允许您在初始数字通过零时“切换方向”:

n = int(input("Enter an integer: "))
s = " "
i = n * -1

while i <= n: 
    num = n - abs(i)

    print(s * num + str(num))
    i += 1
这将产生:
Enter an integer: 3
0
 1
  2
   3
  2
 1
0

关于python - 一个 while 循环来向上和向下计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63787164/

相关文章:

python - 优化执行多次的算法

java - 在 Kotlin 的运行 block 中继续

python - 我无法理解变量在 for 循环之前的作用

c - 求字符串中整数的总和

c++ - 这条语句 "while(a[i]--!=0)"是做什么的?

python - 如何使用 Pandas 对所有 CSV 文件列和行执行数学运算

python - 获取数组python中的最小数字

python - keras model.fit 函数打印的准确率与验证集还是训练集有关?

python - 使用 Pandas 按指定顺序写入 Excel 表格

c++ - while 内打印增量计数变量值