Reputation: 58
Trying to make a program that outputs the sum of integers within a range of integers inclusively. This works, but I am trying to find a way for it to print out the output the way I want it to.
numOne = int(input('enter a number: '))
numTwo = int(input('enter a second number: '))
sum = numOne
for i in range(numOne+1, numTwo+1):
sum += i
print('the sum of the numbers you entered inclusively is = ', sum)
Current output:
enter a number: 10
enter a second number: 15
the sum of the numbers you entered inclusively is = 75
Desired output:
enter a number: 10
enter a second number: 15
the sum of the numbers you entered inclusively is = 75
10 + 11 + 12 + 13 + 14 + 15 = 75
I'm aware that I haven't coded for the chance that one of the numbers is negative, but that's not my concern right now. How do I get the for loop to iterate over the range and print it in a concatenated manner like the desired output? Not really needed, but curious to see how I would do it if I needed to.
Upvotes: 0
Views: 61
Reputation: 78
If the existing code must be kept the same, this will print the last line.
print(' + '.join([str(i) for i in range(numOne, numTwo+1)]), '=', sum)
Upvotes: 0
Reputation: 71542
I suggest using str.join
and the builtin sum
function (note that if you name a variable sum
, it shadows that function):
numOne = int(input('enter a number: '))
numTwo = int(input('enter a second number: '))
nums = range(numOne, numTwo+1)
print(" + ".join(str(n) for n in nums), "=", sum(nums))
enter a number: 10
enter a second number: 15
10 + 11 + 12 + 13 + 14 + 15 = 75
Upvotes: 3
Reputation: 88
This plain loop will do.
for i in range(numOne, numTwo+1):
if i != numTwo:
print(f'{i} + ', end='')
else:
print(f'{i} = {sum}')
Upvotes: 0