LiL_Cj - 1 year ago 165
Python Question

# 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:

``````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. Can anyone help me out with this?

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()
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download