2

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

1
  • - Your print statement should be inside the while loop (i.e. you have to add indentation to it). - The print statement should come before num += 1 Commented May 4, 2021 at 6:27

3 Answers 3

2
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)
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice solution, I like it.
0

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.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.