In: Computer Science
Python Create Loop
1 = 1 1 + 2 = 3 1 + 2 + 3 = 6 1 + 2 + 3 + 4 = 10 1 + 2 + 3 + 4 + 5 = 15
Create a loop in python that makes this pattern
def displayPyramid(n):
#variable declaration
num = 1
#for loop
for i in range(0, n):
num = 1
result = 0
for j in range(0, i+1):
if i > j:
print(num, end=" + ")
else:
print(num, end=" ")
result = result + num
num = num + 1
#display result
print("=", result)
print("\r")
# test code
n = 5
#call method
displayPyramid(n)
OUTPUT:
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15