Reputation: 75
I've created a summation function that takes in a start number and an end number and returns a summed answer between those two points
def print_sum_equations(start_number,end_number):
mySum = 0
num = start_number
while num <= end_number:
mySum += num
num += 1
print (mySum)
print_sum_equations(3,5)
It returns 12 which is correct, however, I want my output to look like the following
3 + 4 + 5 = 12
rather than just returning the answer. Im still new to python and learning how to iterate while loops so any help is appreciated
Upvotes: 2
Views: 1258
Reputation: 155
Pretty new to programming in python, my solution, is pretty simple and easy to read.
def print_sum_equations(start_number,end_number):
mySum = 0
num = start_number
num_list = []
num_list.append(num)
while num <= end_number:
mySum += num
num += 1
num_list.append(num)
print (mySum)
num_list.pop()
print(*num_list, sep="+",end="")
print("="+str(mySum))
print_sum_equations(2,5)
Upvotes: 0
Reputation: 491
def print_sum_equations(start_number,end_number):
vals = [i for i in range(start_number,end_number+1)]
s = sum(vals)
for ind,i in enumerate(vals):
print(f'{i}',end='')
if ind != end_number-start_number:
print(' + ',end='')
else:
print(f' = {s}')
print_sum_equations(3,5)
Upvotes: 2
Reputation: 77827
Use the join
method to get the series from a list of values.
val_list = list(range(start_number, end_number+1))
lhs = ' + '.join(val_list)
print ( lhs + ' = ' + str(sum(val_list)) )
You could also use a list comprehension to get val_list:
val_list = [ n for n in range(start_number, end_number+1) ]
... but list(range(...
is more direct.
Upvotes: 0