使用'for'循环在Python中打印模式

时间:2019-10-06 20:16:29

标签: python-3.x for-loop nested-loops

我尝试了各种程序来获得所需的模式(如下所示)。最接近所需结果的程序如下:

输入:

[06-Oct-2019 16:26:49 America/New_York] PHP Warning:  move_uploaded_file(videos/VSkzuJn0aZYoLvNLJwv3IrFNA9PV1zjfd4MfoXP3rjl1Nm7uW8--Peek 2019-05-20 18-11.mp4): failed to open stream: No such file or directory in /home/myacc/website.com/index.php on line 34

[06-Oct-2019 16:26:49 America/New_York] PHP Warning:  move_uploaded_file(): Unable to move '/tmp/phpTOsPRj' to 'videos/VSkzuJn0aZYoLvNLJwv3IrFNA9PV1zjfd4MfoXP3rjl1Nm7uW8--Peek 2019-05-20 18-11.mp4' in /home/myacc/website.com/index.php on line 34

输出:

for i in range(1,6):
    for j in range(i,i*2):
        print(j, end=' ')
    print( )

必需的输出:

1 
2 3 
3 4 5 
4 5 6 7 
5 6 7 8 9 

我可以得到一些提示以获取所需的输出吗?

注:python的新手。

2 个答案:

答案 0 :(得分:1)

将打印的值存储在循环外,然后在打印后增加

v = 1
lines = 4
for i in range(lines):
    for j in range(i):
        print(v, end=' ')
        v += 1
    print( )

答案 1 :(得分:0)

如果您不想跟踪计数并用数学方法解决这个问题并能够直接计算第n条线,那么您正在寻找的公式就是triangle numbers的公式:

triangle = lambda n: n * (n + 1) // 2
for line in range(1, 5):
    t = triangle(line)
    print(' '.join(str(x+1) for x in range(t-line, t)))
# 1
# 2 3
# 4 5 6
# 7 8 9 10