Crunch
Crunch

Reputation: 125

How to make a number triangle

I'm trying to make a triangle that appears like

1 12 123 1234 12345

This code causes it to just print 1 over and over

def line(n):
    print('1' *n)

def triangle(n):
    for i in range(1,n+1):
        line(i)

Upvotes: 0

Views: 5000

Answers (3)

c4rt0
c4rt0

Reputation: 68

I actually came across same issue @ College :)

Here is my solution :) :

for n in range (1, n):
x = n
for x in range(0,x):
    print(x+1, end='')
print()

Produces exactly what you asked for using nested FOR loop:

1
12
123
1234
12345

Upvotes: 0

Nodak
Nodak

Reputation: 979

You start with an empty string, increment it, and print it through the range.

def line(n):
    triangle = ''
    for i in range(1, n+1):
        triangle = triangle + (str(i))
        print(triangle)
        i+=1

This renders:

>>> line(5)
    1
    12
    123
    1234
    12345
>>> 

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 881645

What about (assuming Python 3):

def line(n):
    for i in range(n):
        print(i+1, end='')
    print()

Upvotes: 3

Related Questions