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.
CodePudding user response:
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
CodePudding user response:
This plain loop will do.
for i in range(numOne, numTwo 1):
if i != numTwo:
print(f'{i} ', end='')
else:
print(f'{i} = {sum}')
CodePudding user response:
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)