1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2013
Posts
2
Rep Power
0

#### Printing Triangular Numbers

Hi, i have a wrote a program with the code:

def triangle(n):
if n<=0:
return 0
else:
return n+triangle(n-1)

To print triangular numbers such as 1,3,6,10..etc.
But im not too sure how im meant to print the actual numbers? Could anybody give me a hand? Thank you
2. Code:
```def triangle(n):
return n*(1+n)//2

for n in range(10):
print('{} {}'.format(n,triangle(n)))```
3. You could do it this way ...
Code:
```def triangle(n):
if n <= 0:
return 0
else:
return n + triangle(n-1)

for n in range(1, 16):
print("%2d --> %d" % (n, triangle(n)))```
4. No Profile Picture
Contributing User
Devshed Novice (500 - 999 posts)

Join Date
May 2009
Posts
667
Rep Power
40
IMHO a for() loop is easier.
Code:
```num=0

for x in range(1, 5):
num += x
print num```
5. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Dec 2012
Posts
114
Rep Power
7
Code:
```from itertools import accumulate
print(*accumulate(range(1, 10)), sep=", ")```
Last edited by Nyktos; February 22nd, 2013 at 12:47 PM.