I'm new to Python and I am trying to make a function to calculate the sum of triangular numbers between lowerbound and upperbound. However, my output can only return the first triangular number between this 2 limit. Thanks for the help!
def is_triangle(num):
if num < 0:
return False
sum = 0
n = 1
while(sum<=num):
sum = sum n
if sum == num:
return True
n =1
return False
def triangle_sum(lower_bound, upper_bound):
sum = 0
for i in range(lower_bound,upper_bound 1):
if is_triangle(i)== True:
sum = i
i =1
return sum
if __name__ == "__main__":
print(triangle_sum(1,10))
CodePudding user response:
def is_triangle(num):
if num < 0:
return False
summ = 0
n = 1
while(summ<=num):
summ = summ n
if summ == num:
return True
n =1
return False
def triangle_sum(lower_bound, upper_bound):
summ = 0
for i in range(lower_bound,upper_bound 1):
if is_triangle(i)== True:
summ = i
i =1
return summ
if __name__ == "__main__":
print(triangle_sum(1,10))
This will be correct as your indentation was wrong. You can learn more about it here,
https://www.programiz.com/python-programming/statement-indentation-comments https://www.python.org/dev/peps/pep-0008/
Also, sum is a keyword in Python, so don't use sum as a variable.
CodePudding user response:
Your return sum was indented to be inside the if in for. It should be directly under the function, that's it!! If you're new to programming in general, then one way to detect such errors is to debug your code. For example, you could have printed the value of 'i' inside the for loop, and noticed that it just stopped after going through just one iteration.
def is_triangle(num):
if num < 0:
return False
sum = 0
n = 1
while(sum <= num):
sum = sum n
if sum == num:
return True
n = 1
return False
def triangle_sum(lower_bound, upper_bound):
sum = 0
for i in range(lower_bound, upper_bound 1):
if is_triangle(i) == True:
sum = i
i = 1
return sum
if __name__ == "__main__":
print(triangle_sum(1, 10))