简体   繁体   中英

Triangular Numbers Using Loops (Python)

I'm currently working on a project that I'm working on, and I'm currently learning about looping. Here is the direction as follows...

Triangular numbers are numbers of objects that could be arranged in a triangle by making rows, with one more object in each row than in the previous row. Write a function that given a number, n, will formulaically compute the nth Triangular number. Write another function that displays the Triangular numbers up to and including n.

The formula states (n(n+1))/(2) or (n^(2)+n)/(2)

So pretty much I think I would need to formulate a function that whatever I enter for n to the equation I would get the answer. However, my question is I don't understand how loops is used in this scenario. I have done the following but I'm getting an error. I think it should very simple right?

n=int(input("Please Enter n:"))
y1=((n**2)+n)/(2)   
print (y1)

I think the code above answers the first question where it formulaically compute the nth Triangular number, given inputing n. However, I'm having a hard time to write a function for the second question where a function that displays the Triangular numbers up to and including n. Thank you very much for your help.

Could be something like this:

def all_triangle_numbers(n):
    for i in range(1, n + 1):   
        print("n = {0}, triangle = {1}".format(i, (i ** 2 + i)//2))

all_triangle_numbers(10)        

You are probably getting an error because of your input() , which should be raw_input() . However, if that is not the case, please state exactly what error you are getting.

Here is some working code:

def triangle(n):
    return ((n**2)+2)/2.0

n = int(raw_input('Please enter an integer: '))
print triangle(n)

Or, to print all the triangle numbers up to and including n :

def all_triangles(n):
    for i in range(1, n+1):
        print ((i**2)+2)/2.0,

n = int(raw_input('Please enter an integer: '))
all_triangles(n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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