gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:56:42 27 4
gpt4 key购买 nike

你如何编写一个程序来从用户整数输入开始向上和向下计数,只使用一个 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/

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