简体   繁体   English

使用嵌套for循环python 3.x的直角三角形

[英]Right triangle using nested for loop python 3.x

I'm trying to output a right triangle with numbers. 我正在尝试输出带有数字的直角三角形。 Here is what I have so far: 这是我到目前为止的内容:

for i in range(1, 10):
    for j in range(i):
    print(i, end='')
print()

My output is this 我的输出是这个

1
22
333
4444
55555
666666
7777777
88888888
999999999

My question is this. 我的问题是这个。 Can I make these numbers run in sequence using a nested for loop example: 我是否可以使用嵌套的for循环示例按顺序运行这些数字:

1
12
123
1234
12345
123456
1234567
12345678
123456789

I've tried about 6 other sets and mostly keep getting the same output or multiple errors. 我尝试了大约6组其他设置,并且大多数情况下都保持相同的输出或多个错误。 Can anyone help me out with this? 谁能帮我这个忙吗?

j can do more than a counter: j可以做的不只是计数器:

for i in range(1, 10):
    for j in range(i):
        print(j + 1, end='')
    print()

You might want to consider what happens next? 您可能要考虑接下来会发生什么? This gives you a few ideas. 这给您一些想法。

import itertools

for i in range(1, 21):
    cycle = itertools.cycle([1,2,3,4,5,6,7,8,9,0])
    for j in range(i):
        print(next(cycle), end="")
    print()

This cycles through the digits giving you output as follows: 这将循环显示数字,为您提供以下输出:

1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
12345678901
123456789012
1234567890123
12345678901234
123456789012345
1234567890123456
12345678901234567
123456789012345678
1234567890123456789
12345678901234567890

Or alternatively: 或者:

for i in range(1, 21):
    for j in range(i):
        print(((j % 10) + 1) % 10, end="")
    print()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM