Here is my original code:
x = input("Please input an integer: ")
x = int(x)
i = 1
sum = 0
while x >= i:
sum = sum + i
i += 1
print(sum)
Here is what the second part is:
b) Modify your program by enclosing your loop in another loop so that you can find consecutive sums. For example , if 5 is entered, you will find five sum of consecutive numbers so that:
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
I have been stuck on this for 3 days now, and I just can’t understand how to do it. I have tried this but to no avail.
while x >= i:
sum_numbers = sum_numbers + i
past_values = range(i)
for ints in past_values:
L = []
L.append(ints)
print(L, "+", i, "=", sum_numbers)
i += 1
Can anyone just help steer my in the correct direction? BTW. it is python 3.3
You could do this in one loop, by using
rangeto define your numbers, andsumto loop through the numbers for you.range(1, x+1)would give me[1, 2, 3, 4, 5], this acts as the controller for how many times we want to print out a sum. So, this for loop will happen 5 times for your example.nums = range(1, i+1)notice we are usingiinstead here, (taken from therangeabove), which I am using to define which number I am up to in the sequence.' + '.join(map(str, nums)):map(str, nums)is used to convert all elements ofnumsinto strings usingstr, since thejoinmethod expects an iterable filled with strings.' + '.joinis used to “join” elements together with a common string, in this case, ‘ + ‘. In cases where there is only 1 element,joinwill just return that element.sum(nums)is giving you the sum of all numbers defined inrange(1, i+1):range(1, 2),sum(nums)= 1range(1, 3),sum(nums)= 3